How To Customize Password Policy in ASP.Net Identity

Introduction

 
Microsoft has released a new version of ASP.NET Identity, 2.0.0-alpha 1. You can refer to ASP.NET Identity Preview to get an idea of this release.
 
In that context, we are here today to create an MVC application using ASP.NET Identity to customize the password to provide better security to the application. You'll learn here to modify the minimum length of the password and to make the entering of numeric and special characters in the password mandatory and disallow recently used passwords.
 
By default, the ASP.NET Identity requires that the minimum length of the password is 6 characters and here we change it to 8. We'll work on the Visual Studio 2013 version and you must update all the assemblies related to the ASP.NET Identity.
 
So, let's proceed with the following sections:
  • Create ASP.NET MVC Application
  • Modifying the Minimum Length
  • Customize Password Validation
Create ASP.NET MVC Application
 
Now we create the MVC application using the following procedure.
 
Step 1: Open Visual Studio 2013 and click on "New Project".
 
Create Web Application in VS 2013
 
Step 2: Select the MVC Project Template to create the application and click "OK".
 
MVC Project Template in VS 2013
 
Step 3: In Solution Explorer, right-click on References and click "Manage NuGet Packages...".
 
NuGet Package Reference
 
Step 4: Select "Include Prerelease" and search for "Identity". Update all the Identity-related packages.
 
Idenetity in NuGet Package
 
After this, you can see in your Pacakages.Config that all the packages are updated. We can also look at the following points to understand how the user is created in the application. You can see the following code in your AccountController class under the Controllers folder:
  1. public async Task<ActionResult> Register(RegisterViewModel model)  
  2. {  
  3.     if (ModelState.IsValid)  
  4.     {  
  5.         var user = new ApplicationUser() { UserName = model.UserName };  
  6.         var result = await UserManager.CreateAsync(user, model.Password);  
  7.         if (result.Succeeded)  
  8.         {  
  9.             await SignInAsync(user, isPersistent: false);  
  10.             return RedirectToAction("Index""Home");  
  11.         }  
  12.         else  
  13.         {  
  14.             AddErrors(result);  
  15.         }  
  16.     }  
  17.    
  18.     // If we got this far, something failed, redisplay form  
  19.     return View(model);  

  • The Account controller uses an instance of the UserManager class. This takes a UserStore class that has persistence-specific API for user management.
  • The preceding method creates a new user. The call to CreateAsync in turn calls the ValidateAsync on the PasswordValidator property for the password validation.
Modifying the Minimum Length
 
Now in this section, we'll modify the minimum length of the password to 8. The PasswordValidator property is used to set the length, this value can be changed. Proceed with the following procedure.
 
Step 1: Add a new folder named IdentityExtentions to the project.
Step 2: Add a new class named AppUserManager in this folder.
 
Adding Class in MVC
 
Step 3: Replace the class code with the code below.
 
First add the following assemblies:
  1. using CustomizePasswordApp.Models;  
  2. using Microsoft.AspNet.Identity;  
  3. using Microsoft.AspNet.Identity.EntityFramework  
  4. Code:  
  5. namespace CustomizePasswordApp.IdentityExtentions  
  6. {  
  7.     public class AppUserManager : UserManager<ApplicationUser>  
  8.     {  
  9.         public AppUserManager()  
  10.             : base(new UserStore<ApplicationUser>(new ApplicationDbContext()))  
  11.         {  
  12.             PasswordValidator = new MinimumLengthValidator(8);  
  13.         }  
  14.     }  

Step 4: Now we need to change the AccountController to use the AppUserManager class. Change the constructor code and class property with the highlighted code below:
  1. public class AccountController: Controller {  
  2.         public AccountController(): this(new AppUserManager()) {}  
  3.         public AccountController(AppUserManager userManager) {  
  4.             UserManager = userManager;  
  5.         }  
  6.   
  7.         public AppUserManager UserManager { get;  
  8.             private set; } 
Step 5: Build the solution and run the application. Now try to register a new user. If the password length is less then 8, you'll get the error as shown below:
 
Password Validation in MvcApp Registeration
 

Customize Password Validation

 
As mentioned above now we'll customize the password in this section. Use the following procedure to do that.
 
Password must have one special and one numeric character
 
Step 1: Add a new class named CustomizePasswordValidation in the IdentityExtensions folder.
 
Step 2: Replace the code with the code below:
  1. using Microsoft.AspNet.Identity;  
  2. using System;  
  3. using System.Text.RegularExpressions;  
  4. using System.Threading.Tasks;  
  5.    
  6. namespace CustomizePasswordApp.IdentityExtentions  
  7. {  
  8.     public class CustomizePasswordValidation : IIdentityValidator<string>  
  9.     {  
  10.         public int LengthRequired { getset; }  
  11.    
  12.         public CustomizePasswordValidation(int length)  
  13.         {  
  14.             LengthRequired = length;  
  15.         }  
  16.    
  17.         public Task<IdentityResult> ValidateAsync(string Item)  
  18.         {  
  19.             if (String.IsNullOrEmpty(Item) || Item.Length < LengthRequired)  
  20.             {  
  21.                 return Task.FromResult(IdentityResult.Failed(String.Format("Minimum Password Length Required is:{0}", LengthRequired)));  
  22.             }  
  23.    
  24.             string PasswordPattern = @"^(?=.*[0-9])(?=.*[!@#$%^&*])[0-9a-zA-Z!@#$%^&*0-9]{10,}$";  
  25.    
  26.             if (!Regex.IsMatch(Item, PasswordPattern))  
  27.             {  
  28.                 return Task.FromResult(IdentityResult.Failed(String.Format("The Password must have at least one numeric and one special character")));  
  29.             }  
  30.    
  31.             return Task.FromResult(IdentityResult.Success);  
  32.         }  
  33.     }  

In the code above, the ValidateAsync method is used to check the password length at first, and then by the regular expression, we can check whether or not the password entered to satisfy the requirements.
 
Step 3: Now we need to provide this validator in the PasswordValidator property of the UserManager. Open the AppUserManager class and change the PasswordValidator property as shown below:
  1. public class AppUserManager : UserManager<ApplicationUser>  
  2. {  
  3.     public AppUserManager()  
  4.         : base(new UserStore<ApplicationUser>(new ApplicationDbContext()))  
  5.     {  
  6.         PasswordValidator = new CustomizePasswordValidation(8);  
  7.     }  

Step 4: Run the application and register a new user that does not meet the requirements.
 
Custom Password Validation in MVC 5
 
Password cannot be reusable
 
While changing the password, we can prevent the user from entering the previous password. Use the following procedure to do that.
 
Step 1: Open the IdentityModels.cs in the Models folder and create a new class named UsedPassword and change the code with the highlighted code as shown below:
  1. using Microsoft.AspNet.Identity.EntityFramework;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.ComponentModel.DataAnnotations;  
  5. using System.ComponentModel.DataAnnotations.Schema;  
  6.    
  7. namespace CustomizePasswordApp.Models  
  8. {  
  9.     public class ApplicationUser : IdentityUser  
  10.     {  
  11.         public ApplicationUser()  
  12.             : base()  
  13.         {  
  14.             UserUsedPassword = new List<UsedPassword>();  
  15.         }  
  16.    
  17.         public virtual IList<UsedPassword> UserUsedPassword { getset; }  
  18.     }  
  19.    
  20.     public class ApplicationDbContext : IdentityDbContext<ApplicationUser>  
  21.     {  
  22.         public ApplicationDbContext()  
  23.             : base("DefaultConnection")  
  24.         {  
  25.         }  
  26.     }  
  27.    
  28.     public class UsedPassword  
  29.     {  
  30.         public UsedPassword()  
  31.         {  
  32.             CreatedDate = DateTimeOffset.Now;  
  33.         }  
  34.    
  35.         [Key, Column(Order = 0)]  
  36.         public string HashPassword { getset; }  
  37.         public DateTimeOffset CreatedDate { getset; }  
  38.         [Key, Column(Order = 1)]  
  39.         public string UserID { getset; }  
  40.         public virtual ApplicationUser AppUser { getset; }  
  41.     }  

In the preceding, we used the UserUsedPassword property to hold the list of user passwords.
 
Step 2: Now we need to store the password hash in the history table when the user is created for the first time. We need to override the existing UserStore now because since the UserStore does not define such a method separately to store the password history. So, add a new class in the IdentityExtensions folder named AppUserStore and add the following code:
  1. using CustomizePasswordApp.Models;  
  2. using Microsoft.AspNet.Identity.EntityFramework;  
  3. using System.Data.Entity;  
  4. using System.Threading.Tasks;  
  5.    
  6. namespace CustomizePasswordApp.IdentityExtentions  
  7. {  
  8.     public class AppUserStore : UserStore<ApplicationUser>  
  9.     {  
  10.         public AppUserStore(DbContext MyDbContext)  
  11.             : base(MyDbContext)  
  12.         {  
  13.         }  
  14.    
  15.         public override async Task CreateAsync(ApplicationUser appuser)  
  16.         {  
  17.             await base.CreateAsync(appuser);  
  18.             await AddToUsedPasswordAsync(appuser, appuser.PasswordHash);  
  19.         }  
  20.    
  21.         public Task AddToUsedPasswordAsync(ApplicationUser appuser, string userpassword)  
  22.         {  
  23.             appuser.UserUsedPassword.Add(new UsedPassword() { UserID = appuser.Id, HashPassword = userpassword });  
  24.             return UpdateAsync(appuser);  
  25.         }  
  26.     }  
  27. }  
In the code above The AddToUsedPasswordAsync() method stores the password in the UsedPassword table separately.
 
Step 3: Now we need to override the ChangePassword and ResetPassword methods in the AppUserManager class with the following code:
  1. public class AppUserManager : UserManager<ApplicationUser>  
  2. {  
  3.     private const int UsedPasswordLimit = 3;  
  4.    
  5.     public AppUserManager()  
  6.         : base(new AppUserStore(new ApplicationDbContext()))  
  7.     {  
  8.         PasswordValidator = new CustomizePasswordValidation(8);  
  9.     }  
  10.    
  11.     public override async Task<IdentityResult> ChangePasswordAsync(string UserID, string CurrentPassword, string NewPassword)  
  12.     {  
  13.         if (await IsPreviousPassword(UserID, NewPassword))  
  14.         {  
  15.             return await Task.FromResult(IdentityResult.Failed("You Cannot Reuse Previous Password"));  
  16.         }  
  17.    
  18.         var Result = await base.ChangePasswordAsync(UserID, CurrentPassword, NewPassword);  
  19.    
  20.        if (Result.Succeeded)  
  21.        {  
  22.            var appStore = Store as AppUserStore;  
  23.            await appStore.AddToUsedPasswordAsync(await FindByIdAsync(UserID), PasswordHasher.HashPassword(NewPassword));  
  24.         }  
  25.    
  26.         return Result;  
  27.     }  
  28.    
  29.     public override async Task<IdentityResult> ResetPasswordAsync(string UserID, string UsedToken, string NewPassword)  
  30.     {  
  31.         if (await IsPreviousPassword(UserID, NewPassword))  
  32.         {  
  33.             return await Task.FromResult(IdentityResult.Failed("You Cannot Reuse Previous Password"));  
  34.         }  
  35.    
  36.         var Result = await base.ResetPasswordAsync(UserID, UsedToken, NewPassword);  
  37.    
  38.         if (Result.Succeeded)  
  39.         {  
  40.             var appStore = Store as AppUserStore;  
  41.             await appStore.AddToUsedPasswordAsync(await FindByIdAsync(UserID), PasswordHasher.HashPassword(NewPassword));  
  42.         }  
  43.    
  44.         return Result;  
  45.    }  
  46.    
  47.    private async Task<bool> IsPreviousPassword(string UserID, string NewPassword)  
  48.    {  
  49.        var User = await FindByIdAsync(UserID);  
  50.    
  51.        if(User.UserUsedPassword.OrderByDescending(up=>up.CreatedDate).Select(up=>up.HashPassword).Take(UsedPasswordLimit).Where(up=>PasswordHasher.VerifyHashedPassword(up, NewPassword) != PasswordVerificationResult.Failed).Any())  
  52.        {  
  53.             return true;  
  54.        }  
  55.    
  56.        return false;  
  57.     } 
Step 4: Now register the local user as specified by the validation requirements.
 
Register in MVC Application
 
Step 5: Change the password using the same password when the user is created. You'll see the error message as shown below:
 
Change Passeord in MVC Application
 

Summary

 
This article described how to customize the validation using the ASP.NET Identity and apply various policies in the application. Thanks for reading.


Similar Articles