How override ASP.NET Core Identity's password policy

后端 未结 4 838
既然无缘
既然无缘 2020-12-04 18:51

By default, ASP.NET Core Identity\'s password policy require at least one special character, one uppercase letter, one number, ...

How can I change this restrictions

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 19:31

    Additional Requirement:

    If you feel this password constraint is not enough, You can define your own conditions by inheriting the PasswordValidator class.

    Sample implementation :

    public class CustomPasswordPolicy : PasswordValidator
        {
            public override async Task ValidateAsync(UserManager manager, AppUser user, string password)
            {
                IdentityResult result = await base.ValidateAsync(manager, user, password);
                List errors = result.Succeeded ? new List() : result.Errors.ToList();
    
                if (password.ToLower().Contains(user.UserName.ToLower()))
                {
                    errors.Add(new IdentityError
                    {
                        Description = "Password cannot contain username"
                    });
                }
                if (password.Contains("123"))
                {
                    errors.Add(new IdentityError
                    {
                        Description = "Password cannot contain 123 numeric sequence"
                    });
                }
                return errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray());
            }
        }
    

    I have override the ValidateAsync method in my class, and inside this method I am implementing my custom password policy.

    Very Very Important

    • The first code line within ValidateAsync()

    IdentityResult result = await base.ValidateAsync(manager, user, password); :

    Validates the password according to the password rules given in the ConfigureServices method of Statup class (the one showed in the old answers for this post)

    • The password validation functionality is defined by the IPasswordValidator interface in the Microsoft.AspNetCore.Identity namespace. So I need to register my ‘CustomPasswordPolicy’ class as the password validator for ‘AppUser’ objects.
        services.AddTransient, CustomPasswordPolicy>();
                services.AddDbContext(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
                services.AddIdentity(opts =>
                {
                    opts.Password.RequiredLength = 8;
                    opts.Password.RequireNonAlphanumeric = true;
                    opts.Password.RequireLowercase = false;
                    opts.Password.RequireUppercase = true;
                    opts.Password.RequireDigit = true;
                }).AddEntityFrameworkStores().AddDefaultTokenProviders();
    
    

    Offical Github Documentation of PasswordValidator.cs (for better understanding): here

提交回复
热议问题