【问题标题】:asp.net core mvc password validatorsasp.net core mvc 密码验证器
【发布时间】:2016-07-03 16:53:29
【问题描述】:

在 asp.net core MVC 中自定义密码验证规则的简单方法是什么?问题与How To Change Password Validation in ASP.Net MVC Identity 2? 的问题完全一样,唯一的区别是我在 Visual Studio 2015 中使用 asp.net CORE MVC(最新版本)。我想删除所有密码验证规则。项目中没有ApplicationUserManager类,也不确定是否可以在Startup.cs文件中自定义UserManager验证规则。

【问题讨论】:

    标签: c# asp.net validation asp.net-core-mvc user-accounts


    【解决方案1】:
    public void ConfigureServices(IServiceCollection services)
    {
         services.AddIdentity<ApplicationUser, IdentityRole>(options =>
                {
                    options.Password.RequireDigit = true;
                    options.Password.RequireLowercase = true;
                    options.Password.RequireNonAlphanumeric = true;
                    options.Password.RequireUppercase = true;
                    options.Password.RequiredLength = 6;
                    options.User.AllowedUserNameCharacters = null;
                })
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
    }
    

    注意:您还应该更改 RegisterViewModel.Password、ResetPasswordViewModel.Password、ChangePasswordViewModel.NewPassword 和 SetPasswordViewModel.NewPassword 中的新设置。 在前端启用新的验证。

    【讨论】:

      【解决方案2】:

      如果您只想禁用某些密码限制(RequireLowercase、RequiredLength 等)- 在 Startup 中配置 IdentityOptions.Password,如下所示:

      services.Configure<IdentityOptions>(o =>
      {
          o.Password.RequiredLength = 12;
      });
      

      如果您想完全更改密码验证逻辑 - 实现 IPasswordValidator 并在 Startup 中注册。

      【讨论】:

        【解决方案3】:

        您还可以使用公共类来自定义错误消息。像这样:

        public class CustomIdentityErrorDescriber : IdentityErrorDescriber
        {
            public override IdentityError PasswordRequiresDigit()
            {
                return new IdentityError
                {
                    Code = nameof(PasswordRequiresDigit),
                    Description = "Your personal describe error message here."
                };
            }
        
        }
        

        在您的 Statup.cs 中,在 ConfigureService 中添加:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<IdentityContext>()
                    .AddErrorDescriber<CustomIdentityErrorDescriber>()
                    .AddDefaultTokenProviders();
        
             //...
        }
        

        【讨论】:

        • 即使问题是关于密码验证而不是消息,这仍然很有用。对于将要使用它的任何人,您只需要一个类并在内部覆盖您要自定义的每个错误描述器,一个 .AddErrorDescriber&lt;ClassName&gt;() 以及
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-03
        • 1970-01-01
        • 2016-09-10
        • 2020-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多