配置 ASP.NET Core 标识Configure ASP.NET Core Identity

ASP.NET Core 标识设置,例如密码策略、 锁定和 cookie 配置使用默认值。ASP.NET Core Identity uses default values for settings such as password policy, lockout, and cookie configuration. 在中,可以重写这些设置Startup类。These settings can be overridden in the Startup class.

标识选项Identity options

IdentityOptions类表示可用于标识系统配置的选项。The IdentityOptions class represents the options that can be used to configure the Identity system. IdentityOptions 必须设置调用AddIdentityAddDefaultIdentityIdentityOptions must be set after calling AddIdentity or AddDefaultIdentity.

声明标识Claims Identity

IdentityOptions.ClaimsIdentity指定ClaimsIdentityOptions与下表中所示的属性。IdentityOptions.ClaimsIdentity specifies the ClaimsIdentityOptions with the properties shown in the following table.

属性Property 描述Description 默认Default
RoleClaimTypeRoleClaimType 获取或设置用于为角色声明的声明类型。Gets or sets the claim type used for a role claim. ClaimTypes.RoleClaimTypes.Role
SecurityStampClaimTypeSecurityStampClaimType 获取或设置用于安全戳声明的声明类型。Gets or sets the claim type used for the security stamp claim. AspNet.Identity.SecurityStamp
UserIdClaimTypeUserIdClaimType 获取或设置用于的用户标识符声明的声明类型。Gets or sets the claim type used for the user identifier claim. ClaimTypes.NameIdentifierClaimTypes.NameIdentifier
UserNameClaimTypeUserNameClaimType 获取或设置用于用户名称声明的声明类型。Gets or sets the claim type used for the user name claim. ClaimTypes.NameClaimTypes.Name

锁定Lockout

在中设置锁定PasswordSignInAsync方法: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();
}

前面的代码基于Login标识模板。The preceding code is based on the Login Identity template.

在中设置锁定选项StartUp.ConfigureServices: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;
});

上述代码会设置IdentityOptions LockoutOptions具有默认值。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指定LockoutOptions与表中所示的属性。IdentityOptions.Lockout specifies the LockoutOptions with the properties shown in the table.

属性Property 描述Description 默认Default
AllowedForNewUsersAllowedForNewUsers 确定是否新用户会被锁定。Determines if a new user can be locked out. true
DefaultLockoutTimeSpanDefaultLockoutTimeSpan 时间量用户已锁定时在锁定时发生。The amount of time a user is locked out when a lockout occurs. 5 分钟5 minutes
MaxFailedAccessAttemptsMaxFailedAccessAttempts 用户已被锁定,如果启用了锁定前的失败的访问尝试数。The number of failed access attempts until a user is locked out, if lockout is enabled. 55

PasswordPassword

默认情况下,标识要求密码包含大写字符、 小写字符、 数字、 和非字母数字字符。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可以设置Startup.ConfigureServicesPasswordOptions 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指定PasswordOptions与表中所示的属性。IdentityOptions.Password specifies the PasswordOptions with the properties shown in the table.

属性Property 描述Description 默认Default
RequireDigitRequireDigit 需要介于 0-9 的密码。Requires a number between 0-9 in the password. true
RequiredLengthRequiredLength 密码最小长度。The minimum length of the password. 66
RequireLowercaseRequireLowercase 要求密码中的小写字符。Requires a lowercase character in the password. true
RequireNonAlphanumericRequireNonAlphanumeric 需要在密码中的非字母数字字符。Requires a non-alphanumeric character in the password. true
RequiredUniqueCharsRequiredUniqueChars 仅适用于 ASP.NET Core 2.0 或更高版本。Only applies to ASP.NET Core 2.0 or later.

要求在密码中非重复字符数。Requires the number of distinct characters in the password.
11
RequireUppercaseRequireUppercase 需要大写字符的密码。Requires an uppercase character in the password. true
属性Property 描述Description 默认Default
RequireDigitRequireDigit 需要介于 0-9 的密码。Requires a number between 0-9 in the password. true
RequiredLengthRequiredLength 密码最小长度。The minimum length of the password. 66
RequireLowercaseRequireLowercase 要求密码中的小写字符。Requires a lowercase character in the password. true
RequireNonAlphanumericRequireNonAlphanumeric 需要在密码中的非字母数字字符。Requires a non-alphanumeric character in the password. true
RequireUppercaseRequireUppercase 需要大写字符的密码。Requires an uppercase character in the password. true

登录Sign-in

下面的代码设置SignIn(为默认值) 的设置:The following code sets SignIn settings (to default values):

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

IdentityOptions.SignIn指定SignInOptions与表中所示的属性。IdentityOptions.SignIn specifies the SignInOptions with the properties shown in the table.

属性Property 描述Description 默认Default
RequireConfirmedEmailRequireConfirmedEmail 需要已确认的电子邮件,登录。Requires a confirmed email to sign in. false
RequireConfirmedPhoneNumberRequireConfirmedPhoneNumber 需要确认的电话号码进行登录。Requires a confirmed phone number to sign in. false

标记Tokens

IdentityOptions.Tokens指定TokenOptions与表中所示的属性。IdentityOptions.Tokens specifies the TokenOptions with the properties shown in the table.

属性Property 描述Description
AuthenticatorTokenProviderAuthenticatorTokenProvider 获取或设置AuthenticatorTokenProvider用于验证身份验证器使用双因素登录名。Gets or sets the AuthenticatorTokenProvider used to validate two-factor sign-ins with an authenticator.
ChangeEmailTokenProviderChangeEmailTokenProvider 获取或设置ChangeEmailTokenProvider用于生成电子邮件更改确认电子邮件中使用的令牌。Gets or sets the ChangeEmailTokenProvider used to generate tokens used in email change confirmation emails.
ChangePhoneNumberTokenProviderChangePhoneNumberTokenProvider 获取或设置ChangePhoneNumberTokenProvider用于生成令牌更改电话号码时使用。Gets or sets the ChangePhoneNumberTokenProvider used to generate tokens used when changing phone numbers.
EmailConfirmationTokenProviderEmailConfirmationTokenProvider 获取或设置用于生成帐户确认电子邮件中使用的令牌的令牌提供程序。Gets or sets the token provider used to generate tokens used in account confirmation emails.
PasswordResetTokenProviderPasswordResetTokenProvider 获取或设置IUserTwoFactorTokenProvider<TUser >用于生成在密码重置电子邮件中使用的令牌。Gets or sets the IUserTwoFactorTokenProvider<TUser> used to generate tokens used in password reset emails.
ProviderMapProviderMap 用于构造用户令牌提供程序与键用作提供程序的名称。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 = false;

});

IdentityOptions.User指定UserOptions与表中所示的属性。IdentityOptions.User specifies the UserOptions with the properties shown in the table.

属性Property 描述Description 默认Default
AllowedUserNameCharactersAllowedUserNameCharacters 在用户名中允许的字符。Allowed characters in the username. abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ
01234567890123456789
-._@+-._@+
RequireUniqueEmailRequireUniqueEmail 要求每个用户必须拥有唯一的电子邮件。Requires each user to have a unique email. false

配置中的应用程序的 cookie Startup.ConfigureServicesConfigure the app's cookie in Startup.ConfigureServices. ConfigureApplicationCookie必须在调用调用AddIdentityAddDefaultIdentityConfigureApplicationCookie 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;
});

有关详细信息,请参阅CookieAuthenticationOptionsFor more information, see CookieAuthenticationOptions.

密码哈希计算器选项Password Hasher options

PasswordHasherOptions 获取和设置进行密码哈希处理的选项。PasswordHasherOptions gets and sets options for password hashing.

选项Option 描述Description
CompatibilityMode 新密码哈希处理时使用的兼容性模式。The compatibility mode used when hashing new passwords. 默认为 IdentityV3Defaults to IdentityV3. 经过哈希处理密码,调用的第一个字节格式标记,指定用于对密码进行加密的哈希算法的版本。The first byte of a hashed password, called a format marker, specifies the version of the hashing algorithm used to hash the password. 验证密码与哈希时VerifyHashedPassword方法选择正确的算法根据第一个字节。When verifying a password against a hash, the VerifyHashedPassword method selects the correct algorithm based on the first byte. 客户端是能够进行身份验证而不考虑的这一版算法用于对密码进行加密。A client is able to authenticate regardless of which version of the algorithm was used to hash the password. 设置兼容性模式将影响的哈希新密码Setting the compatibility mode affects the hashing of new passwords.
IterationCount 使用哈希密码使用 PBKDF2 时的迭代次数。The number of iterations used when hashing passwords using PBKDF2. 此值是时,才使用CompatibilityMode设置为IdentityV3This value is only used when the CompatibilityMode is set to IdentityV3. 值必须是一个正整数,默认值为10000The value must be a positive integer and defaults to 10000.

在以下示例中,IterationCount设置为12000Startup.ConfigureServices:In the following example, the IterationCount is set to 12000 in Startup.ConfigureServices:

// using Microsoft.AspNetCore.Identity;

services.Configure<PasswordHasherOptions>(option =>
{
    option.IterationCount = 12000;
});