REST API中[Authorize]属性授权流程与Token验证机制咨询
Let’s break down the entire flow, including exactly where token validity and expiration are checked, using the Individual User Accounts template you’re working with.
1. Overall Execution Flow of [Authorize]
When a request hits your API:
Step 1: Bearer Token Extraction & Pre-Validation
First, theOAuthBearerAuthenticationMiddleware(configured in yourStartup.Auth.cs) intercepts the request. It scans for theAuthorizationheader with theBearerscheme, extracts the token string, and kicks off validation before the request reaches your controller.Step 2: Authorization Check via
[Authorize]
When the request arrives at yourValuesController(or any controller/method marked with[Authorize]), theAuthorizeAttributetriggers itsOnAuthorizationmethod. This method doesn’t directly validate the token—it relies on the authentication middleware to have already set up a validClaimsPrincipalinHttpContext.User. It simply checks two things:- Is
HttpContext.User.Identity.IsAuthenticatedset totrue? - If you specified roles/claims (e.g.,
[Authorize(Roles = "Admin")]), does the user have the required permissions?
If either check fails, it returns a
401 Unauthorizedresponse immediately.- Is
2. How Token Validity & Expiration Are Checked
The core token validation happens in the authentication middleware stack, not directly in the [Authorize] attribute. Here’s the breakdown of key components:
Key Classes & Methods
OAuthBearerAuthenticationMiddleware&OAuthBearerAuthenticationHandler
These are the workhorses of token validation. The handler’sAuthenticateAsyncmethod handles the heavy lifting:- Extracts the token from the request header.
- Uses
ISecureDataFormat<AuthenticationTicket>(default implementation:TicketDataFormat) to decrypt/deserialize the token into anAuthenticationTicket. - Checks if the ticket’s
ExpiresUtcproperty is in the past. If it is, the token is marked as expired, and authentication fails. - Verifies the token’s integrity (ensuring it hasn’t been tampered with) using the data protector configured in
Startup.Auth.cs(tied to your app’s machine key or a custom key if you’ve set one).
ApplicationOAuthProvider
While this class is mainly responsible for issuing tokens (in theGrantResourceOwnerCredentialsmethod), it defines the token’s expiration time when creating theAuthenticationTicket:var props = new AuthenticationProperties { ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30) // Example expiration }; var ticket = new AuthenticationTicket(identity, props);The
ExpiresUtcvalue here is what the validation middleware checks later to determine if the token is expired.OAuthAuthorizationServerOptions
InStartup.Auth.cs, when configuring the OAuth server, you setAccessTokenExpireTimeSpan(default is 14 days). This value sets the default expiration for all issued tokens, and the validation middleware uses this as a reference via the ticket’sExpiresUtcproperty.
What Triggers a "Token Expired" or "Invalid Token" Response?
- If the token’s
ExpiresUtcis earlier than the current UTC time, the middleware returns a401 Unauthorizedwith a message indicating the token has expired. - If the token’s signature is invalid (tampered with) or it can’t be deserialized correctly, the middleware also returns
401.
Quick Recap
- Request comes in →
OAuthBearerAuthenticationMiddlewarevalidates the token (checks expiration, integrity, etc.). - If valid, it sets
HttpContext.Userto an authenticatedClaimsPrincipal. [Authorize]checks if the user is authenticated (and has required roles/claims).- If all checks pass, the controller method executes; otherwise,
401is returned.
内容的提问来源于stack exchange,提问作者Niteesh Kumar

