Configure ASP.NET Core Identity

ASP.NET Core Identity uses default values for settings such as password policy, lockout, and cookie configuration. These settings can be overridden in the Startup class.

Identity options

The IdentityOptions class represents the options that can be used to configure the Identity system. IdentityOptions must be set after calling AddIdentity or AddDefaultIdentity.

Claims Identity

IdentityOptions.ClaimsIdentity specifies the ClaimsIdentityOptions with the properties shown in the following table.

Property Description Default
RoleClaimType Gets or sets the claim type used for a role claim. ClaimTypes.Role
SecurityStampClaimType Gets or sets the claim type used for the security stamp claim. AspNet.Identity.SecurityStamp
UserIdClaimType Gets or sets the claim type used for the user identifier claim. ClaimTypes.NameIdentifier
UserNameClaimType Gets or sets the claim type used for the user name claim. ClaimTypes.Name

Lockout

Lockout is set in the PasswordSignInAsync method:

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");

    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(Input.Email, 
            Input.Password, Input.RememberMe, 
            lockoutOnFailure: false);
        if (result.Succeeded)
        {
            _logger.LogInformation("User logged in.");
            return LocalRedirect(returnUrl);
        }
        if (result.RequiresTwoFactor)
        {
            return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl,
                Input.RememberMe });
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning("User account locked out.");
            return RedirectToPage("./Lockout");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return Page();
        }
    }

    // If we got this far, something failed, redisplay form
    return Page();
}

The preceding code is based on the Login Identity template.

Lockout options are set in StartUp.ConfigureServices:

services.Configure<IdentityOptions>(options =>
{
    // Default Lockout settings.
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    options.Lockout.MaxFailedAccessAttempts = 5;
    options.Lockout.AllowedForNewUsers = true;
});

The preceding code sets the IdentityOptions LockoutOptions with default values.

A successful authentication resets the failed access attempts count and resets the clock.

IdentityOptions.Lockout specifies the LockoutOptions with the properties shown in the table.

Property Description Default
AllowedForNewUsers Determines if a new user can be locked out. true
DefaultLockoutTimeSpan The amount of time a user is locked out when a lockout occurs. 5 minutes
MaxFailedAccessAttempts The number of failed access attempts until a user is locked out, if lockout is enabled. 5

Password

By default, Identity requires that passwords contain an uppercase character, lowercase character, a digit, and a non-alphanumeric character. Passwords must be at least six characters long. PasswordOptions can be set in Startup.ConfigureServices.

services.Configure<IdentityOptions>(options =>
{
    // Default Password settings.
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequireUppercase = true;
    options.Password.RequiredLength = 6;
    options.Password.RequiredUniqueChars = 1;
});
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
    {
        // Password settings
        options.Password.RequireDigit = true;
        options.Password.RequiredLength = 8;
        options.Password.RequiredUniqueChars = 2;
        options.Password.RequireLowercase = true;
        options.Password.RequireNonAlphanumeric = true;
        options.Password.RequireUppercase = true;
    })
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
    // Password settings
    options.Password.RequireDigit = true;
    options.Password.RequiredLength = 8;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = true;
    options.Password.RequireLowercase = false;
});

IdentityOptions.Password specifies the PasswordOptions with the properties shown in the table.

Property Description Default
RequireDigit Requires a number between 0-9 in the password. true
RequiredLength The minimum length of the password. 6
RequireLowercase Requires a lowercase character in the password. true
RequireNonAlphanumeric Requires a non-alphanumeric character in the password. true
RequiredUniqueChars Only applies to ASP.NET Core 2.0 or later.

Requires the number of distinct characters in the password.
1
RequireUppercase Requires an uppercase character in the password. true
Property Description Default
RequireDigit Requires a number between 0-9 in the password. true
RequiredLength The minimum length of the password. 6
RequireLowercase Requires a lowercase character in the password. true
RequireNonAlphanumeric Requires a non-alphanumeric character in the password. true
RequireUppercase Requires an uppercase character in the password. true

Sign-in

The following code sets SignIn settings (to default values):

services.Configure<IdentityOptions>(options =>
{
    // Default SignIn settings.
    options.SignIn.RequireConfirmedEmail = true;
    options.SignIn.RequireConfirmedPhoneNumber = false;
});
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
    {
        // Signin settings
        options.SignIn.RequireConfirmedEmail = true;
        options.SignIn.RequireConfirmedPhoneNumber = false;
    })
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

IdentityOptions.SignIn specifies the SignInOptions with the properties shown in the table.

Property Description Default
RequireConfirmedEmail Requires a confirmed email to sign in. false
RequireConfirmedPhoneNumber Requires a confirmed phone number to sign in. false

Tokens

IdentityOptions.Tokens specifies the TokenOptions with the properties shown in the table.

Property Description
AuthenticatorTokenProvider Gets or sets the AuthenticatorTokenProvider used to validate two-factor sign-ins with an authenticator.
ChangeEmailTokenProvider Gets or sets the ChangeEmailTokenProvider used to generate tokens used in email change confirmation emails.
ChangePhoneNumberTokenProvider Gets or sets the ChangePhoneNumberTokenProvider used to generate tokens used when changing phone numbers.
EmailConfirmationTokenProvider Gets or sets the token provider used to generate tokens used in account confirmation emails.
PasswordResetTokenProvider Gets or sets the IUserTwoFactorTokenProvider used to generate tokens used in password reset emails.
ProviderMap Used to construct a User Token Provider with the key used as the provider's name.

User

services.Configure<IdentityOptions>(options =>
{
    // Default User settings.
    options.User.AllowedUserNameCharacters =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
    options.User.RequireUniqueEmail = true;

});

IdentityOptions.User specifies the UserOptions with the properties shown in the table.

Property Description Default
AllowedUserNameCharacters Allowed characters in the username. abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
-._@+
RequireUniqueEmail Requires each user to have a unique email. false

Configure the app's cookie in Startup.ConfigureServices. ConfigureApplicationCookie must be called after calling AddIdentity or AddDefaultIdentity.

services.ConfigureApplicationCookie(options =>
{
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.Cookie.Name = "YourAppCookieName";
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
    options.LoginPath = "/Identity/Account/Login";
    // ReturnUrlParameter requires 
    //using Microsoft.AspNetCore.Authentication.Cookies;
    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
    options.SlidingExpiration = true;
});
services.ConfigureApplicationCookie(options =>
{
    options.AccessDeniedPath = "/Account/AccessDenied";
    options.Cookie.Name = "YourAppCookieName";
    options.Cookie.HttpOnly = true; 
    options.ExpireTimeSpan = TimeSpan.FromMinutes(60); 
    options.LoginPath = "/Account/Login";
    // ReturnUrlParameter requires `using Microsoft.AspNetCore.Authentication.Cookies;`
    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
    options.SlidingExpiration = true;
});
services.Configure<IdentityOptions>(options =>
{
    // Cookie settings
    options.Cookies.ApplicationCookie.CookieName = "YourAppCookieName";
    options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(150);
    options.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";
    options.Cookies.ApplicationCookie.AccessDeniedPath = "/Account/AccessDenied";
    options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
    // Requires `using Microsoft.AspNetCore.Authentication.Cookies;`
    options.Cookies.ApplicationCookie.AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.Cookies.ApplicationCookie.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
});

For more information, see CookieAuthenticationOptions.