asp.net核心mvc密码验证器

时间:2016-07-03 16:53:30

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

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

3 个答案:

答案 0 :(得分: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和SetPasswordViewModel.NewPassword中更改新设置。 在前端启用新验证。

答案 1 :(得分:9)

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

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

如果您想彻底更改密码验证逻辑 - 请实施IPasswordValidator并在启动时注册。

答案 2 :(得分: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();

     //...
}