Asp.net Identity PasswordValidator用于最大长度条件

时间:2015-07-06 15:32:02

标签: c# asp.net-identity-2

我有非典型的情况来验证密码以获得最大长度要求。 我正在尝试调整密码验证器以达到我的要求,但密码的最大长度是我遇到的问题。这是我的密码验证器看起来像。

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

有人可以帮我吗?看起来我需要定义一些自定义验证器。

1 个答案:

答案 0 :(得分:7)

您需要使用所需的业务逻辑创建自定义密码验证程序。

然后,您需要将PasswordValidator属性中的ApplicationUserManager设置为新CustomPasswordValidator的实例。

以下是一些来自默认ASP.NET 5 MVC 6模板的示例代码,但同样适用于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;
    }
}