Change password length in MVC 5 Membership

Refracted Paladin picture Refracted Paladin · Nov 1, 2013 · Viewed 9.7k times · Source

Trying to change the default minimum password length to 4 characters. I know, 4!!! Ridiculous, right! Not my call.

Anyway, I've changed it on the RegisterViewModel but that doesn't actually change it. To illustrate I've posted the code below. The ModleState.IsValid returns correctly based on the updated ViewModel. However it then calls UserManager.CreateAsync() which returns False with an error message of "Passwords must be at least 6 characters"

I've followed the steps in this, very, similar post(Change Password...) but it does not work for MVC 5 as far I as I can tell. It still returns the same message.

//
    // 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);
        }

Answer

alex k picture alex k · Nov 1, 2013

As you can see UserManager has public property IIdentityValidator<string> PasswordValidator for password validation which is currently initialized in UserManager's constructor with hardcoded parameter this.PasswordValidator = (IIdentityValidator<string>) new MinimumLengthValidator(6);.

You can set this property with MinimumLengthValidator object with required password length.