The default Identity provider provided in ASP.NET 5 has very strict password rules by default, requiring a lower case character, an upper case character, a non-alphanumeric
What I wanted to do was to customize the password rule so that it should contain characters from at least 2 of the following groups: lower case, upper case, digits and special symbols.
This is not something that I could do by just changing PasswordValidator options:
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
So instead I created a custom validator by extending IIdentityValidator...
First, create a new file CustomPasswordValidator.cs in your Extensions folder:
public class CustomPasswordValidator : IIdentityValidator
{
public int RequiredLength { get; set; }
public CustomPasswordValidator(int length) {
RequiredLength = length;
}
/*
* logic to validate password: I am using regex to count how many
* types of characters exists in the password
*/
public Task ValidateAsync(string password) {
if (String.IsNullOrEmpty(password) || password.Length < RequiredLength)
{
return Task.FromResult(IdentityResult.Failed(
String.Format("Password should be at least {0} characters", RequiredLength)));
}
int counter = 0;
List patterns = new List();
patterns.Add(@"[a-z]"); // lowercase
patterns.Add(@"[A-Z]"); // uppercase
patterns.Add(@"[0-9]"); // digits
// don't forget to include white space in special symbols
patterns.Add(@"[!@#$%^&*\(\)_\+\-\={}<>,\.\|""'~`:;\\?\/\[\] ]"); // special symbols
// count type of different chars in password
foreach (string p in patterns)
{
if (Regex.IsMatch(password, p))
{
counter++;
}
}
if (counter < 2)
{
return Task.FromResult(IdentityResult.Failed(
"Please use characters from at least two of these groups: lowercase, uppercase, digits, special symbols"));
}
return Task.FromResult(IdentityResult.Success);
}
}
Then go to IdentityConfig.cs, and initialize it in Create method:
manager.PasswordValidator = new CustomPasswordValidator(8 /*min length*/);
/*
// You don't need this anymore
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
*/
See my tutorial for more details.