How to Customize Password Policy in ASP.Net Identity
By FoxLearn 2/18/2024 1:30:26 AM 154
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);
- Getting Started with ASP.NET Core 3.0
- How to fix 'Authorization in ASP.NET Core' with 401 Unauthorized
- The name 'Session' does not exist in the current context
- How to create a Toast Notifications in ASP.NET Core
- How to fix Font Awesome WebFont woff2 not working BundleConfig
- How to Minify HTML using WebMarkupMin in ASP.NET Core
- How to Minify HTML using WebMarkupMin in ASP.NET MVC
- How to Minify HTML output from ASP.NET MVC
Categories
Popular Posts
How to sign a powershell script
10/03/2024
How to get Credentials in PowerShell?
10/03/2024
How to implement Jint in C#
09/14/2024