Change password length in MVC 5 Membership
Asked Answered
G

3

14

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);
        }
Gerladina answered 1/11, 2013 at 16:43 Comment(0)
M
16

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.

Meatman answered 1/11, 2013 at 18:0 Comment(0)
S
9

You can set the password properties using the PasswordValidator found in the IdentityConfig.cs file in the App_Start Directory.

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;
    }
Steeplejack answered 20/12, 2014 at 17:43 Comment(0)
C
4

Check the following article at MSDN

Implementing custom password policy using ASP.NET Identity

The suggestion here is to extend the UserManager class in the application and setting the PasswordValidator property in the contructor:

public class MyUserManager : UserManager<ApplicationUser>
{
    public MyUserManager() : 
        base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
    {
        PasswordValidator = new MinimumLengthValidator(4);
    }
}

And then in your controller (or controllers base class) instantiate MyUserManager:

public BaseController() : this(new MyUserManager())
{
}

public BaseController(MyUserManager userManager)
{
  UserManager = userManager;
}

public MyUserManager UserManager { get; private set; }

You may also implement a custom validator to check more complex password rules by implementing IIdentityValidator and replacing the default validator.

Crawl answered 15/1, 2014 at 9:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.