You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

REST API中[Authorize]属性授权流程与Token验证机制咨询

How the [Authorize] Attribute Works with Bearer Token Validation in Your ASP.NET Web API

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, the OAuthBearerAuthenticationMiddleware (configured in your Startup.Auth.cs) intercepts the request. It scans for the Authorization header with the Bearer scheme, 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 your ValuesController (or any controller/method marked with [Authorize]), the AuthorizeAttribute triggers its OnAuthorization method. This method doesn’t directly validate the token—it relies on the authentication middleware to have already set up a valid ClaimsPrincipal in HttpContext.User. It simply checks two things:

    • Is HttpContext.User.Identity.IsAuthenticated set to true?
    • 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 Unauthorized response immediately.

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’s AuthenticateAsync method handles the heavy lifting:

    1. Extracts the token from the request header.
    2. Uses ISecureDataFormat<AuthenticationTicket> (default implementation: TicketDataFormat) to decrypt/deserialize the token into an AuthenticationTicket.
    3. Checks if the ticket’s ExpiresUtc property is in the past. If it is, the token is marked as expired, and authentication fails.
    4. 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 the GrantResourceOwnerCredentials method), it defines the token’s expiration time when creating the AuthenticationTicket:

    var props = new AuthenticationProperties {
        ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30) // Example expiration
    };
    var ticket = new AuthenticationTicket(identity, props);
    

    The ExpiresUtc value here is what the validation middleware checks later to determine if the token is expired.

  • OAuthAuthorizationServerOptions
    In Startup.Auth.cs, when configuring the OAuth server, you set AccessTokenExpireTimeSpan (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’s ExpiresUtc property.

What Triggers a "Token Expired" or "Invalid Token" Response?

  • If the token’s ExpiresUtc is earlier than the current UTC time, the middleware returns a 401 Unauthorized with 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

  1. Request comes in → OAuthBearerAuthenticationMiddleware validates the token (checks expiration, integrity, etc.).
  2. If valid, it sets HttpContext.User to an authenticated ClaimsPrincipal.
  3. [Authorize] checks if the user is authenticated (and has required roles/claims).
  4. If all checks pass, the controller method executes; otherwise, 401 is returned.

内容的提问来源于stack exchange,提问作者Niteesh Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:22:14