By default, ASP.NET Core Identity\'s password policy require at least one special character, one uppercase letter, one number, ...
How can I change this restrictions
Additional Requirement:
If you feel this password constraint is not enough, You can define your own conditions by inheriting the PasswordValidator class.
Sample implementation :
public class CustomPasswordPolicy : PasswordValidator
{
public override async Task ValidateAsync(UserManager manager, AppUser user, string password)
{
IdentityResult result = await base.ValidateAsync(manager, user, password);
List errors = result.Succeeded ? new List() : result.Errors.ToList();
if (password.ToLower().Contains(user.UserName.ToLower()))
{
errors.Add(new IdentityError
{
Description = "Password cannot contain username"
});
}
if (password.Contains("123"))
{
errors.Add(new IdentityError
{
Description = "Password cannot contain 123 numeric sequence"
});
}
return errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray());
}
}
I have override the ValidateAsync method in my class, and inside this method I am implementing my custom password policy.
Very Very Important
IdentityResult result = await base.ValidateAsync(manager, user, password);
:
Validates the password according to the password rules given in the ConfigureServices method of Statup class (the one showed in the old answers for this post)
services.AddTransient, CustomPasswordPolicy>();
services.AddDbContext(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
services.AddIdentity(opts =>
{
opts.Password.RequiredLength = 8;
opts.Password.RequireNonAlphanumeric = true;
opts.Password.RequireLowercase = false;
opts.Password.RequireUppercase = true;
opts.Password.RequireDigit = true;
}).AddEntityFrameworkStores().AddDefaultTokenProviders();
Offical Github Documentation of PasswordValidator.cs (for better understanding): here