ASP.NET Core 驗證的總覽Overview of ASP.NET Core authentication

Mike RousosBy Mike Rousos

驗證是決定使用者身分識別的程式。Authentication is the process of determining a user's identity. 授權 是判斷使用者是否有權存取資源的程式。Authorization is the process of determining whether a user has access to a resource. 在 ASP.NET Core 中,驗證是由 IAuthenticationService 驗證 中介軟體所使用的來處理。In ASP.NET Core, authentication is handled by the IAuthenticationService, which is used by authentication middleware. 驗證服務會使用已註冊的驗證處理常式來完成驗證相關的動作。The authentication service uses registered authentication handlers to complete authentication-related actions. 驗證相關動作的範例包括:Examples of authentication-related actions include:

  • 驗證使用者。Authenticating a user.
  • 當未驗證的使用者嘗試存取受限制的資源時回應。Responding when an unauthenticated user tries to access a restricted resource.

註冊的驗證處理常式和其設定選項稱為「配置」。The registered authentication handlers and their configuration options are called "schemes".

驗證配置的指定方式是在中註冊驗證服務 Startup.ConfigureServicesAuthentication schemes are specified by registering authentication services in Startup.ConfigureServices:

例如,下列程式碼會註冊的驗證服務和處理常式, cookie 以及 JWT 持有人驗證配置:For example, the following code registers authentication services and handlers for cookie and JWT bearer authentication schemes:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => Configuration.Bind("JwtSettings", options))
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => Configuration.Bind("CookieSettings", options));

AddAuthentication參數 JwtBearerDefaults.AuthenticationScheme 是未要求特定配置時,預設要使用的配置名稱。The AddAuthentication parameter JwtBearerDefaults.AuthenticationScheme is the name of the scheme to use by default when a specific scheme isn't requested.

如果使用了多個配置,則 (的授權原則或授權屬性) 可以 指定驗證配置 () 或所依賴的配置 ,以驗證使用者。If multiple schemes are used, authorization policies (or authorization attributes) can specify the authentication scheme (or schemes) they depend on to authenticate the user. 在上述範例中,您 cookie 可以藉由預設指定其名稱 (來使用驗證配置 CookieAuthenticationDefaults.AuthenticationScheme ,但在呼叫) 時可以提供不同的名稱 AddCookieIn the example above, the cookie authentication scheme could be used by specifying its name (CookieAuthenticationDefaults.AuthenticationScheme by default, though a different name could be provided when calling AddCookie).

在某些情況下,的呼叫會 AddAuthentication 由其他擴充方法自動進行。In some cases, the call to AddAuthentication is automatically made by other extension methods. 例如,在使用時 ASP.NET Core IdentityAddAuthentication 會在內部呼叫。For example, when using ASP.NET Core Identity, AddAuthentication is called internally.

Startup.Configure 由呼叫 UseAuthentication 應用程式上的擴充方法,即可在中新增驗證中介軟體 IApplicationBuilderThe Authentication middleware is added in Startup.Configure by calling the UseAuthentication extension method on the app's IApplicationBuilder. 呼叫會 UseAuthentication 註冊使用先前註冊之驗證配置的中介軟體。Calling UseAuthentication registers the middleware which uses the previously registered authentication schemes. UseAuthentication 與要驗證之使用者相依的任何中介軟體之前呼叫。Call UseAuthentication before any middleware that depends on users being authenticated. 使用端點路由時,的呼叫 UseAuthentication 必須移至:When using endpoint routing, the call to UseAuthentication must go:

  • 之後 UseRouting ,您就可以使用路由資訊進行驗證決策。After UseRouting, so that route information is available for authentication decisions.
  • 之前 UseEndpoints ,會先驗證使用者,然後再存取端點。Before UseEndpoints, so that users are authenticated before accessing the endpoints.

驗證概念Authentication Concepts

驗證負責提供 ClaimsPrincipal 授權以進行許可權決策。Authentication is responsible for providing the ClaimsPrincipal for authorization to make permission decisions against. 有多個驗證配置方法可選取哪一個驗證處理常式負責產生一組正確的宣告:There are multiple authentication scheme approaches to select which authentication handler is responsible for generating the correct set of claims:

不會自動探查架構。There is no automatic probing of schemes. 如果未指定預設配置,則必須在授權屬性中指定配置,否則會擲回下列錯誤:If the default scheme is not specified, the scheme must be specified in the authorize attribute, otherwise, the following error is thrown:

InvalidOperationException:未指定 authenticationScheme,而且找不到 DefaultAuthenticateScheme。InvalidOperationException: No authenticationScheme was specified, and there was no DefaultAuthenticateScheme found. 您可以使用 AddAuthentication (string defaultScheme) 或 AddAuthentication (Action < AuthenticationOptions configureOptions) 來設定預設配置 > 。The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).

驗證配置Authentication scheme

驗證配置可以選取哪些驗證處理常式負責產生正確的宣告集。The authentication scheme can select which authentication handler is responsible for generating the correct set of claims. 如需詳細資訊,請參閱 使用特定配置進行授權For more information, see Authorize with a specific scheme.

驗證配置是對應至的名稱:An authentication scheme is a name which corresponds to:

  • 驗證處理常式。An authentication handler.
  • 用於設定該特定處理常式實例的選項。Options for configuring that specific instance of the handler.

配置可作為一種機制,用來參考相關處理常式的驗證、挑戰和禁止行為。Schemes are useful as a mechanism for referring to the authentication, challenge, and forbid behaviors of the associated handler. 例如,授權原則可以使用配置名稱來指定 (或配置) 應該用來驗證使用者的驗證配置。For example, an authorization policy can use scheme names to specify which authentication scheme (or schemes) should be used to authenticate the user. 設定驗證時,通常會指定預設的驗證配置。When configuring authentication, it's common to specify the default authentication scheme. 除非資源要求特定配置,否則會使用預設配置。The default scheme is used unless a resource requests a specific scheme. 也可以:It's also possible to:

  • 指定要用於驗證、挑戰和禁止動作的不同預設配置。Specify different default schemes to use for authenticate, challenge, and forbid actions.
  • 使用 原則配置將多個配置結合成一個。Combine multiple schemes into one using policy schemes.

驗證處理常式Authentication handler

驗證處理常式:An authentication handler:

根據驗證配置的設定和傳入的要求內容,驗證處理常式:Based on the authentication scheme's configuration and the incoming request context, authentication handlers:

  • AuthenticationTicket如果驗證成功,則表示使用者身分識別的結構物件。Construct AuthenticationTicket objects representing the user's identity if authentication is successful.
  • 如果驗證失敗,則傳回「沒有結果」或「失敗」。Return 'no result' or 'failure' if authentication is unsuccessful.
  • 在使用者嘗試存取資源時,有挑戰和禁止動作的方法:Have methods for challenge and forbid actions for when users attempt to access resources:
    • 他們未獲授權,無法存取 (禁止) 。They are unauthorized to access (forbid).
    • 未經驗證 (挑戰) 。When they are unauthenticated (challenge).

AuthenticateAuthenticate

驗證配置的驗證動作會負責根據要求內容來建立使用者的身分識別。An authentication scheme's authenticate action is responsible for constructing the user's identity based on request context. 它會傳回 AuthenticateResult ,指出驗證是否成功,以及使用者在驗證票證中的身分識別。It returns an AuthenticateResult indicating whether authentication was successful and, if so, the user's identity in an authentication ticket. 請參閱 AuthenticateAsyncSee AuthenticateAsync. 驗證範例包括:Authenticate examples include:

  • cookie從建立使用者身分識別的驗證配置 cookie 。A cookie authentication scheme constructing the user's identity from cookies.
  • JWT 持有人配置還原序列化和驗證 JWT 持有人權杖,以建立使用者的身分識別。A JWT bearer scheme deserializing and validating a JWT bearer token to construct the user's identity.

挑戰Challenge

當未驗證的使用者要求需要驗證的端點時,會在授權中叫用驗證挑戰。An authentication challenge is invoked by Authorization when an unauthenticated user requests an endpoint that requires authentication. 例如,當匿名使用者要求受限的資源,或按一下登入連結時,就會發出驗證挑戰。An authentication challenge is issued, for example, when an anonymous user requests a restricted resource or clicks on a login link. 授權會使用指定的驗證配置 (s) 來叫用挑戰,如果未指定,則會使用預設值。Authorization invokes a challenge using the specified authentication scheme(s), or the default if none is specified. 請參閱 ChallengeAsyncSee ChallengeAsync. 驗證挑戰範例包括:Authentication challenge examples include:

  • 將 cookie 使用者重新導向至登入頁面的驗證配置。A cookie authentication scheme redirecting the user to a login page.
  • JWT 持有人配置傳回401結果與 www-authenticate: bearer 標頭。A JWT bearer scheme returning a 401 result with a www-authenticate: bearer header.

挑戰動作應該讓使用者知道要使用哪個驗證機制來存取要求的資源。A challenge action should let the user know what authentication mechanism to use to access the requested resource.

禁止Forbid

當已驗證的使用者嘗試存取不允許存取的資源時,授權會呼叫驗證配置的禁止動作。An authentication scheme's forbid action is called by Authorization when an authenticated user attempts to access a resource they are not permitted to access. 請參閱 ForbidAsyncSee ForbidAsync. 驗證禁止的範例包括:Authentication forbid examples include:

  • 將 cookie 使用者重新導向至表示禁止存取之頁面的驗證配置。A cookie authentication scheme redirecting the user to a page indicating access was forbidden.
  • JWT 持有人配置傳回403結果。A JWT bearer scheme returning a 403 result.
  • 重新導向至使用者可要求存取資源之頁面的自訂驗證配置。A custom authentication scheme redirecting to a page where the user can request access to the resource.

禁止的動作可讓使用者知道:A forbid action can let the user know:

  • 它們是經過驗證的。They are authenticated.
  • 他們不允許存取要求的資源。They aren't permitted to access the requested resource.

請參閱下列連結以取得挑戰和禁止的差異:See the following links for differences between challenge and forbid:

每個租使用者的驗證提供者Authentication providers per tenant

ASP.NET Core framework 沒有內建解決方案可進行多租使用者驗證。ASP.NET Core framework does not have a built-in solution for multi-tenant authentication. 雖然客戶當然可以使用內建功能來撰寫,但我們建議客戶基於此目的來查看 Orchard CoreWhile it's certainly possible for customers to write one, using the built-in features, we recommend customers to look into Orchard Core for this purpose.

Orchard Core 為:Orchard Core is:

  • 以 ASP.NET Core 為基礎的開放原始碼模組化和多租使用者應用程式架構。An open-source modular and multi-tenant app framework built with ASP.NET Core.
  • 內容管理系統 (CMS) 以該應用程式架構為基礎。A content management system (CMS) built on top of that app framework.

如需每個租使用者的驗證提供者範例,請參閱 Orchard Core 來源。See the Orchard Core source for an example of authentication providers per tenant.

其他資源Additional resources