ASP.NET Identity, require 'strong' passwords
Solution 1
You could use the RegularExpressionAttribute together with the rules from this answer:
Regex to validate password strength
Solution 2
You can configure password requirements in App_Start\IdentityConfig.cs
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 4,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
Solution 3
Another option is to create an implementation of IIdentityValidator<string>
and assign it to the PasswordValidator
property of your UserManager
. It only has one method, ValidateAsync
and you can define any sort of password validation you like in there.. I know this doesn't have some of the same advantages as using attributes in you model class as far as automatic client side validation, but just thought I would put this out there as an alternate for anyone who comes along.
e.g.
public class CustomPasswordValidator : IIdentityValidator<string>
{
public int MinimumLength { get; private set; }
public int MaximumLength { get; private set; }
public CustomPasswordValidator(int minimumLength, int maximumLength)
{
this.MinimumLength = minimumLength;
this.MaximumLength = maximumLength;
}
public Task<IdentityResult> ValidateAsync(string item)
{
if (!string.IsNullOrWhiteSpace(item)
&& item.Trim().Length >= MinimumLength
&& item.Trim().Length <= MaximumLength)
return Task.FromResult(IdentityResult.Success);
else return Task.FromResult(IdentityResult.Failed("Password did not meet requrements."));
}
}
ledgeJumper
Am developer. love hate love writing things in javascript.
Updated on December 19, 2020Comments
-
ledgeJumper over 3 years
Perhaps my googlin' skills are not so great this morning, but I can't seem to find how to set up different password requirements (rather than min/max length) with a new asp.net mvc5 project using individual user accounts.
[Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; }
I don't know what password requirements I want to do just yet, but likely a combination of min length and requiring one lowercase, on capital letter, and a number.
Any idea how I can accomplish this (via model attributes preferably)?