更改MVC 5成员身份中的密码长度



尝试将默认的最小密码长度更改为4个字符。我知道,4!!!可笑,对吧!不是我的决定。

无论如何,我已经在RegisterViewModel上更改了它,但这实际上并没有改变它。为了说明问题,我发布了下面的代码。ModleState.IsValid根据更新后的ViewModel正确返回。然而,它随后调用UserManager.CreateAsync(),返回False并返回错误消息"密码必须至少为6个字符">

我遵循了这篇非常类似的文章(更改密码…(中的步骤,但据我所知,它不适用于MVC 5。它仍然返回相同的消息。

//
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName, LastLogin = model.LastLogin };

// This is where it 'fails' on the CreateAsync() call
                    var result = await UserManager.CreateAsync(user, model.Password);
                    if (result.Succeeded)
                    {
                        await SignInAsync(user, isPersistent: false);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        AddErrors(result);
                    }
                }
            // If we got this far, something failed, redisplay form
            return View(model);
        }
正如您所看到的,UserManager具有用于密码验证的公共属性IIdentityValidator<string> PasswordValidator,该属性当前在UserManager的构造函数中使用硬编码参数this.PasswordValidator = (IIdentityValidator<string>) new MinimumLengthValidator(6);初始化。

您可以使用具有所需密码长度的MinimumLengthValidator对象设置此属性。

您可以使用App_Start目录中IdentityConfig.cs文件中的PasswordValidator设置密码属性。

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 PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = false,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };
        // 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;
    }

查看MSDN 上的以下文章

使用ASP。NET标识

这里的建议是在应用程序中扩展UserManager类,并在构造函数中设置PasswordValidator属性

public class MyUserManager : UserManager<ApplicationUser>
{
    public MyUserManager() : 
        base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
    {
        PasswordValidator = new MinimumLengthValidator(4);
    }
}

然后在您的控制器(或控制器基类(中实例化MyUserManager:

public BaseController() : this(new MyUserManager())
{
}
public BaseController(MyUserManager userManager)
{
  UserManager = userManager;
}
public MyUserManager UserManager { get; private set; }

您还可以通过实现IIdentityValidator并替换默认验证器来实现自定义验证器,以检查更复杂的密码规则。

相关内容

最新更新