Custom Password Policy in ASP.NET Identity

How to Create Custom Password Policy in ASP.NET Identity

In this article, I am going to discuss How to Create Custom Password Policy in ASP.NET Identity. Please read our previous article where we discussed How to Reset User Password in ASP.NET Identity using Forgot Password.

Password Policy in ASP.NET Identity:

By default, ASP.NET Identity requires that passwords must contain an Uppercase Character (A-Z), a lowercase character (a-z), a digit (0-9), and a non-alphanumeric character. ASP.NET Identity also requires that passwords must be at least 6 characters long. If you don’t follow these password requirements while adding a new user, ASP.NET Identity will consider the entered password as invalid and will give you the following error.

Password Policy in ASP.NET Identity

Where is this Password Policy Defined?

This Password Policy is defined inside the IdentityConfig.cs file. If you open the IdentityConfig.cs file, then you will see the Create method of the ApplicationUserManager class and inside this method, the following PasswordValidator logic is implemented.

Where is this Password Policy Defined?

The meaning of each property is as follows:

  1. RequiredLength: This property Specifies the Minimum required length of the password.
  2. RequireNonLetterOrDigit: This property Specifies whether a non-letter or digit character is required or not.
  3. RequireDigit: This property Specifies whether a digit (‘0’ – ‘9’) in the password is required or not.
  4. RequireLowercase: This property Specifies whether a lower-case letter (‘a’ – ‘z’) in the password is required or not.
  5. RequireUppercase: This property Specifies whether a lower upper letter (‘A’ – ‘Z’) in the password is required or not.
Creating Custom Password Validator in ASP.NET Identity:

Instead of using the built-in PasswordValidator validator, now we want to use our own custom validator with ASP.NET Identity. We want the password to follow the following policies.

  1. Password should be of minimum 8 Characters.
  2. It should have both Upper-Case (A-Z) and Lower-Case Characters (a-z).
  3. Password should contain at least one digit (0-9).
  4. Password should contain at least one special character (!@#$%^&*).

For this, we need to create our own custom validator. So, a class file with the name CustomPasswordValidator.cs and then copy and paste the following code into it. Here, you can see, this class is inherited from the IIdentityValidator interface and provides an implementation for the ValidateAsync method. The following example code is self-explained, so please go through the comment lines for a better understanding.

using Microsoft.AspNet.Identity;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace AspNetIdentityWithNewProject.Models
{
    public class CustomPasswordValidator : IIdentityValidator<string>
    {
        public int MinLength { get; set; }

        //While Creating CustomPasswordValidator Instance we need to pass the Minimum Length of the Password
        public CustomPasswordValidator(int minLength)
        {
            MinLength = minLength;
        }

        // Validate Password: count how many types of characters exists in the password  
        // Provide Implementation for the ValidateAsync method of IIdentityValidator Interface
        public Task<IdentityResult> ValidateAsync(string password)
        {
            //First Check the Minimum Length Validator
            if (string.IsNullOrEmpty(password) || password.Length < MinLength)
            {
                return Task.FromResult(IdentityResult.Failed($"Password Too Short, Minimum {MinLength} Character Required"));
            }

            int counter = 0;

            //Create a List of String to store the different patterns to be checked in the password
            List<string> patterns = new List<string>
            {
                @"[a-z]", // Lowercase  
                @"[A-Z]", // Uppercase  
                @"[0-9]", // Digits  
                @"[!@#$%^&*\(\)_\+\-\={}<>,\.\|""'~`:;\\?\/\[\]]" // Special Symbols
            };

            // Count Type of Different Chars present in the Password  
            foreach (string p in patterns)
            {
                if (Regex.IsMatch(password, p))
                {
                    counter++;
                }
            }

            //If the counter is less than or equals to 3, means password doesnot contain all the required patterns
            if (counter <= 3)
            {
                return Task.FromResult(IdentityResult.Failed("Please Use a Combination of Lowercase, Uppercase, Digits, Special Symbols Characters"));
            }
            return Task.FromResult(IdentityResult.Success);
        }
    }
}

With the above CustomPasswordValidator class, now open the IdentityConfig.cs class file, go to the Create method of the ApplicationUserManager class, and then instead of using the PasswordValidator class, now you can use the CustomPasswordValidator class and to the constructor, you need to pass the minimum length of the password as shown in the below image.

Creating Custom Password Validator in ASP.NET Identity

Now, with the above changes in place, now run the application and try to register a user with the password abcd1234 and you should get the following error message.

How to Create Custom Password Policy Validator in ASP.NET Identity

Now, try to register the user with a password of less than 8 characters and you should get the following error message.

How to Create Custom Password Policy Validator in ASP.NET Identity

In the next article, I am going to discuss Username and Email Policy in ASP.NET Identity. Here, in this article, I try to explain How to Create Custom Password Policy Validator in ASP.NET Identity. I hope you enjoy this Password Policy Validator in ASP.NET Identity article.

Leave a Reply

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