Abi P
Abi P

Reputation: 1450

Asp.net Identity PasswordValidator for max length condition

I am having atypical situation to validate the password for maximum length requirement. I am trying to tweak the password validator to achieve my requirement but the max length for a password is something I am having trouble with. here is what my password validator looking like.

manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false, //Overrode per requirement
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
            MaxLength = 10 //TODO:Max length requirement                
        };

Can anyone help me here? Looks like I need to define some custom validator.

Upvotes: 2

Views: 6989

Answers (1)

Martin
Martin

Reputation: 1634

You need to create a custom password validator with the required business logic.

Then you need to set the PasswordValidator inside the ApplicationUserManager property to a instance of your new CustomPasswordValidator.

Here is some example code that comes from the default ASP.NET 5 MVC 6 template, but the same applies for MVC 5:

CustomPasswordValidator:

public class CustomPasswordValidator : PasswordValidator
{
    public int MaxLength { get; set; }

    public override async Task<IdentityResult> ValidateAsync(string item)
    {
        IdentityResult result = await base.ValidateAsync(item);

        var errors = result.Errors.ToList();

        if (string.IsNullOrEmpty(item) || item.Length > MaxLength)
        {
            errors.Add(string.Format("Password length can't exceed {0}", MaxLength));
        }

        return await Task.FromResult(!errors.Any()
         ? IdentityResult.Success
         : IdentityResult.Failed(errors.ToArray()));
    }
}

ApplicationUserManager:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new CustomPasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
            MaxLength = 10
        };

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

Upvotes: 9

Related Questions