How do I define the password rules for Identity in ASP.NET 5 MVC 6 (vNext)?

C#asp.netasp.net Mvcasp.net Identityasp.net Core-Mvc

C# Problem Overview


The default Identity provider provided in ASP.NET 5 has very strict password rules by default, requiring a lower case character, an upper case character, a non-alphanumeric character, and a number. I am looking for a way to change the password requirements for the provider.

Previously in ASP.NET 4, the provider could be configured via the Web.config XML file, as previously answered. However ASP.NET 5 uses the new code based configuration pattern and it is unclear how to configure the identity.

How can I change the password requirements for my application?

C# Solutions


Solution 1 - C#

I actually ended up figuring this out, it turns out you need to supply AddDefaultIdentity with a suitable lambda expression that configures the IdentityOptions it provides. This is done inside the ConfigureServices method within the Startup class, like so:

public class Startup {
    public void ConfigureServices(IServiceCollection services) {
        
        // Add Identity services to the services container.
        services.AddDefaultIdentity<ApplicationIdentityDbContext, ApplicationUser, IdentityRole>(Configuration,
            o => {
                o.Password.RequireDigit = false;
                o.Password.RequireLowercase = false;
                o.Password.RequireUppercase = false;
                o.Password.RequireNonLetterOrDigit = false;
                o.Password.RequiredLength = 7;
            });
    }
}

Update 2:

The above was true in the beta1 versions of the framework, in the latest rc1 beta5 it has changed slightly to:

services.AddIdentity<ApplicationUser, IdentityRole>(o => {
    // configure identity options
    o.Password.RequireDigit = false;
    o.Password.RequireLowercase = false;
    o.Password.RequireUppercase = false;
    o.Password.RequireNonAlphanumeric = false;
    o.Password.RequiredLength = 6;
})
.AddEntityFrameworkStores<ApplicationIdentityDbContext>()
.AddDefaultTokenProviders();

Solution 2 - C#

If you have set up a new Web project with Individual User Accounts go to:

App_Start -> IdentityConfig.cs

There you can edit the following defaults:

manager.PasswordValidator = new PasswordValidator
{
    RequiredLength = 6,
    RequireNonLetterOrDigit = true,
    RequireDigit = true,
    RequireLowercase = true,
    RequireUppercase = true,
};

Solution 3 - C#

in startup.cs:

   services.AddIdentity<ApplicationUser, IdentityRole>(x =>
        {
            x.Password.RequiredLength = 6;
            x.Password.RequireUppercase = false;
            x.Password.RequireLowercase = false;
            x.Password.RequireNonAlphanumeric = false;
        }).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

Solution 4 - C#

What I wanted to do was to customize the password rule so that it should contain characters from at least 2 of the following groups: lower case, upper case, digits and special symbols.

This is not something that I could do by just changing PasswordValidator options:

manager.PasswordValidator = new PasswordValidator
{
    RequiredLength = 6,
    RequireNonLetterOrDigit = false,
    RequireDigit = false,
    RequireLowercase = false,
    RequireUppercase = false,
 };

So instead I created a custom validator by extending IIdentityValidator...

First, create a new file CustomPasswordValidator.cs in your Extensions folder:

public class CustomPasswordValidator : IIdentityValidator<string>
{
    public int RequiredLength { get; set; }
    public CustomPasswordValidator(int length) {
        RequiredLength = length;
    }

    /* 
     * logic to validate password: I am using regex to count how many 
     * types of characters exists in the password
     */
    public Task<IdentityResult> ValidateAsync(string password) {
        if (String.IsNullOrEmpty(password) || password.Length < RequiredLength)
        {
            return Task.FromResult(IdentityResult.Failed(
                $"Password should be at least {RequiredLength} characters"));
        }

        int counter = 0;
        List<string> patterns = new List<string>();
        patterns.Add(@"[a-z]");                                          // lowercase
        patterns.Add(@"[A-Z]");                                          // uppercase
        patterns.Add(@"[0-9]");                                          // digits
        // don't forget to include white space in special symbols
        patterns.Add(@"[!@#$%^&*\(\)_\+\-\={}<>,\.\|""'~`:;\\?\/\[\] ]"); // special symbols

        // count type of different chars in password
        foreach (string p in patterns)
        {
            if (Regex.IsMatch(password, p))
            {
                counter++;
            }
        }

        if (counter < 2)
        {
            return Task.FromResult(IdentityResult.Failed(
                "Please use characters from at least two of these groups: lowercase, uppercase, digits and special symbols"));
        }

        return Task.FromResult(IdentityResult.Success);
    }
}

Then go to IdentityConfig.cs, and initialize it in Create method:

manager.PasswordValidator = new CustomPasswordValidator(8 /*min length*/);
        /*
        // You don't need this anymore
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };
        */

See my tutorial for more details.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyanView Question on Stackoverflow
Solution 1 - C#RyanView Answer on Stackoverflow
Solution 2 - C#OgglasView Answer on Stackoverflow
Solution 3 - C#sadeghhpView Answer on Stackoverflow
Solution 4 - C#Hooman BahreiniView Answer on Stackoverflow