Search code examples
visual-studio-2015asp.net-coreasp.net-identityasp.net-identity-3

ASP.NET Identity - how to change password requirements when creating user programmatically


I'm using default ASP.NET Core 1.1 template with Individual User Accounts authentication. The following code on VS2015 is complaining about the password requirements (such as length requirements, upper case, lower case etc.). I know we can set these requirements on the built-in RegisterViewModel by using DataAnnotations. But since I'm creating the users programmatically without using any ViewModel, the DataAnnotations will not work. Question: How can I change the password requirements and be able to run the following code:

List<String> usersList = GetAllUsers();

foreach (string s in usersList)
{
    var user = new ApplicationUser { UserName = s, UserRole = "TestRole" };
    var result = await _userManager.CreateAsync(user, "testpassword");
}

Solution

  • You can add options in the AddIdentity method...

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.Password.RequireDigit = false;
                options.Password.RequireLowercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequiredLength = 1;
                options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@.";
            })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
    
        services.AddMvc();
    
        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
    }