首页 文章

asp.net核心mvc密码验证器

提问于
浏览
8

在asp.net核心MVC中自定义密码验证规则的简便方法是什么?问题就像有人在这里How To Change Password Validation in ASP.Net MVC Identity 2?唯一不同的是我在Visual Studio 2015中使用 asp.net CORE MVC (最新版本) . 我想删除所有密码验证规则 . 项目中没有 ApplicationUserManager 类,我也可以在 Startup.cs 文件中自定义UserManager验证规则 .

3 回答

  • 9

    如果你想简单地禁用一些密码限制(RequireLowercase,RequiredLength等) - 在Startup中配置 IdentityOptions.Password ,如下所示:

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

    如果要完全更改密码验证逻辑 - 实现IPasswordValidator并在启动时注册它 .

  • 12
    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 and SetPasswordViewModel.NewPassword. 中更改新设置以在前端启用新验证 .

  • 0

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

    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();
    
         //...
    }
    

相关问题