40

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)?

ledgeJumper
  • 3,560
  • 14
  • 45
  • 92
  • 1
    Will you use MembershipProvider? Using it you can set PasswordStrengthRegularExpression property to define your password strength rules - http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider.passwordstrengthregularexpression(v=vs.110).aspx – giacomelli Jan 06 '14 at 15:38
  • @giacomelli I am using the new Identity provider. Unless I am mistaken I don't believe this will work. I do not have the membership entry in my web.config – ledgeJumper Jan 06 '14 at 15:42
  • 1
    Think carefully about doing this. I use a set of passwords and it's really annoying when the one I want is disallowed by a site because it doesn't match their rules, although it is in fact a strong password. I now have a list of passwords written down, which is not what people were after I hope... – simon at rcl Jan 06 '14 at 16:00
  • @simonatrcl I completely agree. I am trying to figure out how to do it, but for the app I am going to attempt to convince my client to not set up restrictions other that min characters. I loathe sites that make me use weird passwords that are outside of my usual list. (looking at you, various credit card companies) – ledgeJumper Jan 06 '14 at 16:04
  • 1
    :) Show them this: http://xkcd.com/936/ - it's true! – simon at rcl Jan 06 '14 at 16:12
  • Already did! She seems fairly intelligent, so I think I will be able to avoid Tr0ub4dor&3 like passwords. – ledgeJumper Jan 06 '14 at 16:17

4 Answers4

110

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,
};
Sergei Shvets
  • 1,676
  • 1
  • 14
  • 12
  • 1
    I did altered the code, like you mentioned, for `public static ApplicationUserManager Create(...)` in App_Start\IdentityConfig.cs only to find (really) later this Q and realize the StringLength parameter for Password property of Identity.Models.RegisterViewModel overlaps with the RequiredLength mentioned above, so unless I change the setting in both places there is no impact. I would have been stuck if it was for the combination of this Q and your A – DavideB Sep 23 '14 at 09:07
  • 2
    Where would you configure this in a WebForms project? – TrevorBrooks Jan 28 '16 at 19:14
  • 1
    Yes! This should be the accepted answer. In WebForms you will find this code in public static ApplicationUserManager Create (...) – Ignacio May 04 '16 at 22:33
  • one little problem. you cannot add a data annotation to UserViewModel to enforce password rules. Why there is no a dataannotation as PasswordValidator to put in UserViewModel? – akd Jun 30 '17 at 11:42
9

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."));

    }
}
Scott Gartner
  • 862
  • 14
  • 22
Excommunicated
  • 1,252
  • 8
  • 14
7

You could use the RegularExpressionAttribute together with the rules from this answer:

Regex to validate password strength

Community
  • 1
  • 1
Andreas
  • 1,355
  • 9
  • 15
0
/*Passwords must be at least min. 8 and max. 16 characters in length, 
minimum of 1 lower case letter [a-z] and 
a minimum of 1 upper case letter [A-Z] and
a minimum of 1 numeric character [0-9] and
a minimum of 1 special character: $ @ $ ! % * ? & + = # 
PASSWORD EXAMPLE : @Password1 
*/
pass = TextBoxPss1.Text;  

Regex regex = new Regex("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&+=#]) [A-Za-z\\d$@$!%*?&+=#]{8,16}$");
    Match match = regex.Match(pass);

    if (match.Success)
    {TextBoxPss1.Text = "OK" }
CRC Pro
  • 19
  • 4