在MVC 5 Membership中更改密码长度

时间:2013-11-01 16:43:52

标签: .net simplemembership asp.net-mvc-5 asp.net-identity

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

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

我已经按照这个非常类似的帖子(Change Password...)中的步骤进行了操作,但就我所知,它对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);
        }

3 个答案:

答案 0 :(得分:14)

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

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

答案 1 :(得分: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;
    }

答案 2 :(得分:4)

在MSDN上查看以下文章

Implementing custom password policy using 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并替换默认验证程序来实现自定义验证程序以检查更复杂的密码规则。