asp.net core mvc password validators

 ̄綄美尐妖づ 提交于 2019-11-29 18:41:11

问题


What is the easy way to customize password validation rules in asp.net core MVC? The problem is exactly like someone had here How To Change Password Validation in ASP.Net MVC Identity 2? the only difference is that I'm using asp.net CORE MVC (latest build) with Visual Studio 2015. I'd like to remove all password validation rules. There is no ApplicationUserManager class in the project, also I'm not sure if it's possible to customize UserManager validation rules in the Startup.cs file.


回答1:


If you want simply disable some password restrictions (RequireLowercase, RequiredLength etc) - configure IdentityOptions.Password in Startup, like this:

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

If you want completely change password validation logic - implement IPasswordValidator and register it in Startup.




回答2:


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

Note: You should also change your new settings in RegisterViewModel.Password, ResetPasswordViewModel.Password, ChangePasswordViewModel.NewPassword and SetPasswordViewModel.NewPassword. to enable the new validation on front end.




回答3:


Also you can use a public class to customize your errors messages. Like this:

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

}

In your Statup.cs, in ConfigureService add:

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

     //...
}


来源:https://stackoverflow.com/questions/38172195/asp-net-core-mvc-password-validators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!