asp.net 核心 mvc 密码验证器

asp.net core mvc password validators

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

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

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

如果您想完全更改密码验证逻辑 - 实施 IPasswordValidator 并在 Startup.

中注册它
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 中的新设置。 在前端启用新验证。

您还可以使用 public class 来自定义您的错误消息。像这样:

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();

     //...
}