Dot-Net
在 MVC 5 Membership 中更改密碼長度
嘗試將預設最小密碼長度更改為 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; }