asp.net identity

来源:互联网 发布:战舰世界2017岛风数据 编辑:程序博客网 时间:2024/05/17 09:07

想要给自己创建的程序,添加用户和权限,今天开始看下asp.net identity

参考资料:http://asp.net/identity

asp.net的用户系统,从2005年开始主要有4个,asp.net membership,asp.net simple membership,asp.net universal provider和asp.net identity

目前的asp.net identity是2.0 ,和1.0相比改动较大。

可以在项目属性里开启ssl登录,并配置项目只允许ssl访问,在controller中配置需要ssl访问,可以通过如下方式

[RequireHttps]

publicclassHomeController:Controller{

publicActionResultIndex(){

returnView();

}

}

或者在filterConfig.cs中配置全局启用https

Add the Authorize filter and the RequireHttps filter to the application. An alternative approach is to add theAuthorize attribute and theRequireHttps attribute to each controller, but it's considered a security best practice to apply them to the entire application. By adding them globally, every new controller and action method you add will automatically be protected, you won't need to remember to apply them. For more information see Securing your ASP.NET MVC App and the new AllowAnonymous Attribute. Open the App_Start\FilterConfig.cs file and replace the RegisterGlobalFilters method with the following (which adds the two filters):

    public static void    RegisterGlobalFilters(GlobalFilterCollection filters)    {        filters.Add(new HandleErrorAttribute());        filters.Add(new System.Web.Mvc.AuthorizeAttribute());        filters.Add(new RequireHttpsAttribute());    }


看到的大部分文字都是配置社交账号的,基本的application 账号,反而提到很少。

默认情况下,在identityModels.cs中可以配置数据库连接,dbcontext。

在AccountViewModels.cs中配置可以配置注册、登录时需要提供那些信息。

这些字段名,不知道是不是可以自己随便取得。

1.默认创建的程序,注册可以,登录出现以下错误

 @Html.ActionLink("注册", "Register")(如果你没有本地帐户)。

默认产生的代码有bug,把(如果你没有本地帐户)。  注释掉就可以了

因为不准备采用其他方式登录,login.cshtml中的这部分代码可以删除

<div class="col-md-4">
        <section id="socialLoginForm">
            @Html.Partial("_ExternalLoginsListPartial", new { Action = "ExternalLogin", ReturnUrl = ViewBag.ReturnUrl })
        </section>
    </div>

经过上面的设置,所有的网页都必须要登录才能访问了。把首页改成支持匿名访问。

在你想支持匿名的方法前加[AllowAnonymous]即可。account模块已经自动加上了。

下面,添加用户 角色,系统有admin,instructor,student 3种角色。

直接打开aspnetroles表添加即可3种角色即可。

也可以在seed中写。问题出来了,configure.cs中的seed方法

 protected override void Seed(tenhours.DAL.cmsContext context){},context中只有自己定义的类,没有identity默认设置的类。

运行Enable-Migrations  ,会提示发现多个上下文,好像一次只能配置一个上下文的迁移。

Enable-Migrations -ContextTypeName tenhours.Models.ApplicationDbContext -EnableAutomaticMigrations

对上下文tenhours.models.applicationdbcontext启用自动迁移数据库。
       

发现identity中id不是自动加1 的int类型,而是用guid,这个方法好。

密码是hash码,asp.net中hash码

identity中的规则比自己的models要复杂很多。

identity中的seed方法可以这样写

  var userManager = new UserManager<ApplicationUser>(
                 new UserStore<ApplicationUser>(
                     new ApplicationDbContext()));
            var roleManager = new RoleManager<IdentityRole>(
                new RoleStore<IdentityRole>(
                    new ApplicationDbContext()));
            string roleAdmin = "Admin";
            string roleInstructor = "Instructor";
            string roleStudent = "Student";
           
            if (!roleManager.RoleExists(roleAdmin))
               {
                   var roleresult = roleManager.Create(new IdentityRole(roleAdmin));
               }
            if (!roleManager.RoleExists(roleInstructor))
            {
                var roleresult = roleManager.Create(new IdentityRole(roleInstructor));
            }
            if (!roleManager.RoleExists(roleStudent))
            {
                var roleresult = roleManager.Create(new IdentityRole(roleStudent));
            }
          
            var user = new ApplicationUser();
            user.UserName = "admin";
           var userresult= userManager.Create(user, "123456");
            if(userresult.Succeeded){
                var result = userManager.AddToRole(user.Id, roleAdmin);
            }
              
为了防止代码被自动覆盖,可以把上面的代码放在一个common类中 写成一个静态方法initUser,然后再seed中直接调用即可。

自动产生的代码中尽量不要放自己写的代码,被覆盖掉就碉堡了。。

下面,来限制某些页面只能由admin和instructor打开。

只要指定在controller中的对应方法前加[Authorize(roles=“admin,instructor”)]即可。

在看identity的代码时,发现很多地方都使用了await async,简单的说,用async把一个方法标记为异步方法。异步方法的返回结果是task<>类型的。

如果程序接下去的处理要用到异步方法返回的结果,则用await someasyncresult,来等待。

也就是说程序调用了async方法后不会等待,一直到遇到await 。

所以可以用async方法异步调用10个网页,之后等待调用完成。非常美妙,把需要并发的任务,通过async 和await 关键字就简单的完成了。

下面是微软演示程序,配合注释,很容易懂。

  1. public partial class MainWindow : Window  
  2. {  
  3.     // Mark the event handler with async so you can use await in it.  
  4.     private async void StartButton_Click(object sender, RoutedEventArgs e)  
  5.     {  
  6.         // Call and await separately.  
  7.         //Task<int> getLengthTask = AccessTheWebAsync();  
  8.         //// You can do independent work here.  
  9.         //int contentLength = await getLengthTask;  
  10.         int contentLength = await AccessTheWebAsync();  
  11.         resultsTextBox.Text +=  
  12.             String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);  
  13.     }  
  14.   
  15.     // Three things to note in the signature:  
  16.     //  - The method has an async modifier.   
  17.     //  - The return type is Task or Task<T>. (See "Return Types" section.)  
  18.     //    Here, it is Task<int> because the return statement returns an integer.  
  19.     //  - The method name ends in "Async."  
  20.     async Task<int> AccessTheWebAsync()  
  21.     {   
  22.         // You need to add a reference to System.Net.Http to declare client.  
  23.         HttpClient client = new HttpClient();  
  24.   
  25.         // GetStringAsync returns a Task<string>. That means that when you await the  
  26.         // task you'll get a string (urlContents).  
  27.         Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");  
  28.   
  29.         // You can do work here that doesn't rely on the string from GetStringAsync.  
  30.         DoIndependentWork();  
  31.   
  32.         // The await operator suspends AccessTheWebAsync.  
  33.         //  - AccessTheWebAsync can't continue until getStringTask is complete.  
  34.         //  - Meanwhile, control returns to the caller of AccessTheWebAsync.  
  35.         //  - Control resumes here when getStringTask is complete.   
  36.         //  - The await operator then retrieves the string result from getStringTask.  
  37.         string urlContents = await getStringTask;  
  38.   
  39.         // The return statement specifies an integer result.  
  40.         // Any methods that are awaiting AccessTheWebAsync retrieve the length value.  
  41.         return urlContents.Length;  
  42.     }  
  43.   
  44.     void DoIndependentWork()  
  45.     {  
  46.         resultsTextBox.Text += "Working . . . . . . .\r\n";  
  47.     }  
  48. }  


0 0
原创粉丝点击