How to Customize Password Policy in ASP.Net Identity
By FoxLearn 2/18/2024 1:30:26 AM 43
This post shows you how to customize password policy in ASP.NET MVC Identity to provide better security to your application.
By default, ASP.NET MVC Identity requires a minimum password length of 6 characters and here we change it. To do that you need to create a CustomPasswordValidator class, then implement the IIdentityValidator interface.
public class CustomPasswordValidator : IIdentityValidator<string> { public int RequiredLength { get; set; } public CustomPasswordValidator(int length) { RequiredLength = length; } public Task<IdentityResult> ValidateAsync(string password) { if (String.IsNullOrEmpty(password) || password.Length < RequiredLength) { return Task.FromResult(IdentityResult.Failed( String.Format("Password should be at least {0} characters", RequiredLength))); } int counter = 0; List<string> patterns = new List<string>(); patterns.Add(@"[a-z]"); // lowercase patterns.Add(@"[A-Z]"); // uppercase patterns.Add(@"[0-9]"); // digits patterns.Add(@"[!@#$%^&*\(\)_\+\-\={}<>,\.\|""'~`:;\\?\/\[\]]"); // special symbols //check patterns foreach (string p in patterns) { if (Regex.IsMatch(password, p)) counter++; } if (counter < 2) { return Task.FromResult(IdentityResult.Failed( "Please enter your password at least two lowercase letters, uppercase letters, number letters and special symbols.")); } return Task.FromResult(IdentityResult.Success); } }
You can use Regex to check your pattern. The Regex class represents the regular expression engine of the .NET Framework. It can be used to quickly parse large amounts of text to find specific character patterns to extract, edit, replace or delete text substrings.
Open the IdentityConfig.cs the modify PasswordValidator as shown below
manager.PasswordValidator = new CustomPasswordValidator(7);
- How to fix "InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager'"
- How to fix 'IMvcBuilder' does not contain a definition for 'AddNewtonsoftJson'
- ASP.NET Core: How to Create RDLC Report in ASP.NET Core
- ASP.NET MVC: Free Responsive Templates
- How to fix Assets file 'project.assets.json' not found
- How to fix 'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer'
- How to set cookie ValidationInterval in ASP.NET Core
- How to fix LoginPath not working in ASP.NET Core
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024