How to Customize Password Policy in ASP.Net Identity
By FoxLearn 2/18/2024 1:30:26 AM 280
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);
- Content Negotiation in Web API
- How to fix 'InvalidOperationException: Scheme already exists: Bearer'
- How to fix System.InvalidOperationException: Scheme already exists: Identity.Application
- Add Thread ID to the Log File using Serilog
- Handling Exceptions in .NET Core API with Middleware
- InProcess Hosting in ASP.NET Core
- Limits on ThreadPool.SetMinThreads and SetMaxThreads
- Controlling DateTime Format in JSON Output with JsonSerializerOptions
Categories
Popular Posts
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
Spica Admin Dashboard Template
11/18/2024