【问题标题】:Change password length in MVC 5 Membership在 MVC 5 Membership 中更改密码长度
【发布时间】:2013-11-12 22:04:30
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以使用 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;
          }
      

      【讨论】:

        【解决方案3】:

        查看 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 并替换默认验证器来实现自定义验证器来检查更复杂的密码规则。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-24
          • 2011-02-10
          • 1970-01-01
          • 2022-01-09
          • 1970-01-01
          • 2013-01-21
          相关资源
          最近更新 更多