Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Identity, require 'strong' passwords

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

like image 356
ledgeJumper Avatar asked Jan 06 '14 15:01

ledgeJumper


2 Answers

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, }; 
like image 89
Sergei Shvets Avatar answered Sep 21 '22 00:09

Sergei Shvets


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."));      } } 
like image 45
Excommunicated Avatar answered Sep 19 '22 00:09

Excommunicated