設定 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

密碼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中可設定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;
});