14

尝试将默认最小密码长度更改为 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);
        }
4

3 回答 3

15

如您所见,密码验证的UserManager公共属性IIdentityValidator<string> PasswordValidator当前在UserManager构造函数中使用硬编码参数进行初始化this.PasswordValidator = (IIdentityValidator<string>) new MinimumLengthValidator(6);

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

于 2013-11-01T18:00:30.703 回答
9

您可以使用 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;
    }
于 2014-12-20T17:43:57.743 回答
4

查看 MSDN 上的以下文章

使用 ASP.NET Identity 实现自定义密码策略

这里的建议是在应用程序中扩展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和替换默认验证器来实现自定义验证器来检查更复杂的密码规则。

于 2014-01-15T09:19:48.597 回答