zoukankan      html  css  js  c++  java
  • Asp.Net MVC Identity 2.2.1 使用技巧(二)

    之前我们看到了新生成的项目中跟identity有关的有四个文件,这些文件是基础功能,并未开启identity的全部功能。现在我们先启用角色功能。

    1、在App_Start文件夹中的IdentityConfig.cs中添加角色控制器。

    在namespace xxx内(即最后一个“}”前面)添加 角色控制类

    代码如下:

     1 //配置此应用程序中使用的应用程序角色管理器。RoleManager 在 ASP.NET Identity 中定义,并由此应用程序使用。
     2     public class ApplicationRoleManager : RoleManager<IdentityRole>
     3     {
     4         public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
     5             : base(roleStore)
     6         {
     7         }
     8 
     9         public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    10         {
    11             return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
    12         }
    13     }

    2、修改startup文件,启用角色管理器(RoleManager)。    

        打开App_Start文件夹中的startup.auth.cs 在  public void ConfigureAuth(IAppBuilder app) 方法中(约为19行左右)加入  app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

    修改完成后的代码如下:

    1 // 配置数据库上下文、用户管理器和登录管理器,以便为每个请求使用单个实例
    2             app.CreatePerOwinContext(ApplicationDbContext.Create);
    3             app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    4             app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); //添加的角色管理器
    5             app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

    这里最基本的角色功能启用就完成了。

    可选操作1:

    这个可选操作用于在创建网站的时候,像网站数据库中添加一个管理用户。如果直接发布给别人用的话 还是挺不错的,自己用的话可以省略掉。

    一、在identityconfig.cs可以配置添加一个用户(用户名为:“admin@123.com”,密码为“Admin@123456”)并把该用户添加到角色("Admin")中。

    代码如下:

     1 public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext> 
     2     {
     3         protected override void Seed(ApplicationDbContext context) {
     4             InitializeIdentityForEF(context);
     5             base.Seed(context);
     6         }
     7 
     8         //创建用户名为admin@123.com,密码为“Admin@123456”并把该用户添加到角色组"Admin"中
     9         public static void InitializeIdentityForEF(ApplicationDbContext db) {
    10             var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
    11             var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
    12             const string name = "admin@123.com";//用户名
    13             const string password = "Admin@123456";//密码
    14             const string roleName = "Admin";//用户要添加到的角色组
    15 
    16             //如果没有Admin用户组则创建该组
    17             var role = roleManager.FindByName(roleName);
    18             if (role == null) {
    19                 role = new IdentityRole(roleName);
    20                 var roleresult = roleManager.Create(role);
    21             }
    22         
    23        //如果没有admin@123.com用户则创建该用户
    24             var user = userManager.FindByName(name);
    25             if (user == null) {
    26                 user = new ApplicationUser { UserName = name, Email = name };
    27                 var result = userManager.Create(user, password);
    28                 result = userManager.SetLockoutEnabled(user.Id, false);
    29             }
    30 
    31             // 把用户admin@123.com添加到用户组Admin中
    32             var rolesForUser = userManager.GetRoles(user.Id);
    33             if (!rolesForUser.Contains(role.Name)) {
    34                 var result = userManager.AddToRole(user.Id, role.Name);
    35             }
    36         }
    37     }

    二、修改Models文件夹中IdentityModels.cs

                在public class ApplicationDbContext : IdentityDbContext<ApplicationUser>类中添加初始化设置。

    代码如下:

    1 static ApplicationDbContext()
    2         {
    3             // 在第一次启动网站时初始化数据库添加管理员用户凭据和admin 角色到数据库
    4             Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    5         }

    可选操作2:自定义用户名和密码验证规则

    自定义用户名验证规则,例如QQ.com。

    要完成这个功能我们可以添加自定义的用户验证策略,只要继承继承UserValidator<T> 然后 Override ValidateAsync 方法。

    1、为了管理方便,先创建一个文件夹“zidingyi”,在文件夹中添加一个名称为“CustomUserValidator.cs”的类文件,写入代码如下:

     1    //自定义用户名email只支持QQ.com域名
     2 
     3     public class CustomUserValidator : UserValidator<ApplicationUser>
     4     {
     5 
     6         public CustomUserValidator(ApplicationUserManager mgr)
     7             : base(mgr)
     8         {
     9         }
    10         //重写ValidateAsync方法
    11         public override async Task<IdentityResult> ValidateAsync(ApplicationUser user)
    12         {
    13             IdentityResult result = await base.ValidateAsync(user);
    14 
    15             if (!user.Email.ToLower().EndsWith("@QQ.com"))
    16             {
    17                 var errors = result.Errors.ToList();
    18                 errors.Add("Email 地址只支持QQ.com域名");
    19                 result = new IdentityResult(errors);
    20             }
    21             return result;
    22         }
    23     }

    2、将自定义的UserValidator 附加到User Manger 对象上,操作如下:

         打开App_Start/Identityconfig.cs 找到public static ApplicationUserManager Create()方法,把manager.UserValidator = new UserValidator<ApplicationUser>(manager)中的UserValidator替换为manager.UserValidator = new zidingyi.CustomUserValidator(manager); 

    可选操作3:自定义密码验证规则

    自定义密码验证规则,如禁止类似“12345”的密码。

    同上,完成这个我们只要继承PasswordValidator 并且Override ValidateAsync方法即可。

    1、在文件夹“zidingyi”,添加一个名称为“CustomPasswordValidator.cs”的类文件,写入代码如下:

     1 //自定义用户密码禁止类似12345  记得添加对应的using
     2     public class CustomPasswordValidator : PasswordValidator
     3     {
     4         //重写ValidateAsync方法
     5         public override async Task<IdentityResult> ValidateAsync(string pass)
     6         {
     7             IdentityResult result = await base.ValidateAsync(pass);
     8             if (pass.Contains("12345"))
     9             {
    10                 var errors = result.Errors.ToList();
    11                 errors.Add("密码不能为连续的数字");
    12                 result = new IdentityResult(errors);
    13             }
    14             return result;
    15         }
    16     }

    2、将自定义的PasswordValidator 附加到UserManger 对象上,操作如下:

         打开App_Start/Identityconfig.cs 找到public static ApplicationUserManager Create()方法,把manager.PasswordValidator = new PasswordValidator(54行)中的PasswordValidator替换为manager.PasswordValidator = new zidingyi.CustomPasswordValidator; 

  • 相关阅读:
    Istio安装配置及使用
    Istio介绍
    Rancher管理k8s集群
    EFK部署
    常见日志收集方案及相关组件
    Prometheus Pushgateway
    Prometheus监控拓展
    Prometheus PromQL语法
    开始新工作了
    SpringBlade 新系统 运行
  • 原文地址:https://www.cnblogs.com/chonghanyu/p/6364127.html
Copyright © 2011-2022 走看看