-1

I added other password rules using opts inside the Program.cs file. Only one password rule can't be defined here, which is that the password has to start with a letter. Right now, it doesn't care if the password starts with a number or a letter.

services.Configure<IdentityOptions>(opts => {
opts.Password.RequiredLength = 8;
opts.Password.RequireLowercase = true;
#     });

How can I add this password policy using C# and ASP.NET Core MVC 6?

Would it help if I use opts.Password.RequireNonLetterOrDigit?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 2
    Why should the password start with a letter? Why does it matter? – Progman Mar 04 '23 at 15:21
  • 1
    Does this answer your question? [How do I define the password rules for Identity in ASP.NET 5 MVC 6 (vNext)?](https://stackoverflow.com/questions/27831597/how-do-i-define-the-password-rules-for-identity-in-asp-net-5-mvc-6-vnext) – Progman Mar 04 '23 at 15:25
  • [Password.RequireNonLetterOrDigit](https://learn.microsoft.com/en-us/previous-versions/aspnet/mt151568(v=vs.108)) has docs. Why do you think they exist? – Luuk Mar 04 '23 at 15:25

1 Answers1

1

If you can't find an option that does what you need, you can write a custom password validator:

public class PasswordStartsWithLetterValidator<TUser> : PasswordValidator<TUser>
    where TUser : class
{
    public override Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string? password)
    {
        if (!(string.IsNullOrEmpty(password) || char.IsLetter(password[0])))
        {
            return Task.FromResult(
                IdentityResult.Failed(new IdentityError
                {
                    Code = "FirstCharNotLetter",
                    Description = "The first character in the password has to be a letter."
                }));
        }

        return base.ValidateAsync(manager, user, password);
    }
}

Register the password validator in the services collection:

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddPasswordValidator<PasswordStartsWithLetterValidator<IdentityUser>>();
nikstra
  • 556
  • 3
  • 9