Customize the Password Rule in ASP.NET Identity

It is quite common that we need to customize out password rules in ASP.NET identity. The best way for this is to use our own PasswordValidator in ApplicationUserManager. By this way, everywhere we need to create a new password (new user registering or password changing), the validator will always be called and we can make the code consistent and reusable.

Firstly we have a look at the built-in PasswordValidator:

var manager = new ApplicationUserManager(new UserStore(context.Get()));
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
    RequiredLength = 6,
    RequireNonLetterOrDigit = true,
    RequireDigit = true,
    RequireLowercase = true,
    RequireUppercase = true,
};

In the template code, VS create a PasswordValidator instance and assign the properties in the object.

Then we have a deeper look into PasswordValidator class:

public class PasswordValidator : IIdentityValidator<string>

We can see that the PasswordValidator implement the IIdentityValidator<string> interface. We need to create my own validator, so we have to create a class CustomPasswordValidator which also implement the IIdentityValidator<string> interface:

public class CustomPasswordValidator : IIdentityValidator<string>

Then have a look at IIdentityValidator<string> interface:

namespace Microsoft.AspNet.Identity
{
    //
    // Summary:
    //     Used to validate an item
    //
    // Type parameters:
    //   T:
    public interface IIdentityValidator<in T>
    {
        //
        // Summary:
        //     Validate the item
        //
        // Parameters:
        //   item:
        Task<IdentityResult> ValidateAsync(T item);
    }
}

There is only one method in the interface. We need to implement ValidateAsync method. The method should be passed in the item to be validated and return an IdentityResult object. Then we can write our own validator CustomPasswordValidator:

namespace Cobra.Identity.IdentityExtensions
{
    public class CustomPasswordValidator : IIdentityValidator<string>
    {
        public int RequiredLength { get; set; }

        public CustomPasswordValidator(int length)
        {
            RequiredLength = length;
        }

        public Task<IdentityResult> ValidateAsync(string item)
        {
            if (String.IsNullOrEmpty(item) || item.Length < RequiredLength)
            {
                return Task.FromResult(IdentityResult.Failed(String.Format("Password should be of length {0}", RequiredLength)));
            }

            //^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$
            string patternUppercase = @"[A-Z]";

            if (!Regex.IsMatch(item, patternUppercase))
            {
                return Task.FromResult(IdentityResult.Failed("At least one uppercase letter is required"));
            }

            string patternLowercase = @"[a-z]";

            if (!Regex.IsMatch(item, patternLowercase))
            {
                return Task.FromResult(IdentityResult.Failed("At least one lowercase letter is required"));
            }

            string patternDigit = @"[0-9]";
            string patternSpecial = @"[_\W]";

            if (!Regex.IsMatch(item, patternDigit) && !Regex.IsMatch(item, patternSpecial))
            {
                return Task.FromResult(IdentityResult.Failed("At least one number or special character is required"));
            }

            return Task.FromResult(IdentityResult.Success);
        }
    }
}

Then in IdentityConfiguration.cs, we instantiate the class and assign it to manager.PasswordValidator.

// Configure validation logic for passwords
const int passwordLength = 8;
manager.PasswordValidator = new CustomPasswordValidator(passwordLength);

 

6 comments

  1. My brother suggested I might like this website. He was
    entirely right. This post actually made my day.
    You cann’t imagine simply how much time I had spent for this info!

    Thanks!

  2. Hiya very nice web site!! Guy .. Beautiful .. Superb
    .. I will bookmark your website and take the feeds additionally?
    I am happy to find numerous useful information here within the put up,
    we want develop extra strategies in this regard, thanks for sharing.
    . . . . .

  3. Thanks on your marvelous posting! I certainly enjoyed reading it, you’re a great author.I will make
    sure to bookmark your blog and will often come back later in life.
    I want to encourage you continue your great work, have a nice holiday weekend!

  4. Thanks for finally talking about >Customize the Password Rule in ASP.NET Identity – Nickys Tech Blog <Loved it!

  5. I am actually happy to read this website posts which consists of tons of valuable information, thanks for providing such data.

  6. www.afar.com says:

    I enjoy what you guys tend to be up too. This type
    of clever work and coverage! Keep up the great works
    guys I’ve included you guys to blogroll.

Leave a Reply

Your email address will not be published. Required fields are marked *