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

MVC 5调用Web API 2.0时的Token存储、传递与过期校验问题

Hey there, let's walk through each of your questions about handling API tokens in MVC 5 and Web API 2.0—this is a super common scenario, so I’ll break it down clearly for you.

1. Where to Store the Token in Your MVC 5 Client

You’ve got a few solid options, each with tradeoffs around security and use case:

  • HttpOnly Cookies (Recommended): This is the most secure choice because the cookie can’t be accessed by client-side JavaScript, which mitigates XSS attack risks. Here’s how to set it in MVC:
    var apiTokenCookie = new HttpCookie("ApiAuthToken")
    {
        Value = yourGeneratedToken,
        HttpOnly = true,
        Secure = true, // Enable this if you're using HTTPS (always do this in production!)
        Expires = DateTime.Now.AddHours(1) // Match your token's expiry time
    };
    Response.Cookies.Add(apiTokenCookie);
    
  • Session State: If your MVC app uses server-side sessions, you can store the token here. Just note that sessions rely on a default cookie (ASP.NET_SessionId), and you’ll need session sharing if you’re running in a load-balanced environment. Example:
    Session["ApiAuthToken"] = yourGeneratedToken;
    
  • LocalStorage/SessionStorage: Good for MVC views that act like single-page apps, but carries XSS risk since JavaScript can read the token. Use this only if you have strict XSS protections in place. Set it with JS:
    localStorage.setItem('apiAuthToken', 'your-generated-token-value');
    

2. How to Pass the Token to Your Web API

The standard approach for REST APIs is using the Authorization header, but you can also leverage cookies if your API and MVC app share a domain:

  • Bearer Token in Authorization Header: This is the industry standard for token-based auth. In MVC, use HttpClient to attach the header when calling your API:
    using (var httpClient = new HttpClient())
    {
        // Fetch the token from your chosen storage (e.g., cookie)
        var token = Request.Cookies["ApiAuthToken"]?.Value;
        
        if (!string.IsNullOrEmpty(token))
        {
            httpClient.DefaultRequestHeaders.Authorization = 
                new AuthenticationHeaderValue("Bearer", token);
        }
        
        var response = await httpClient.GetAsync("https://your-api-domain.com/api/secure-endpoint");
    }
    
  • Cookie (Same Domain/Subdomain): If your API and MVC app live on the same domain or subdomain, browsers will automatically send the cookie with API requests. For cross-domain scenarios, you’ll need to configure CORS to allow credentials.

3. How to Validate Token Expiry in Web API 2

You can either use built-in OAuth middleware (if you’re using ASP.NET Identity) or create a custom filter for manual validation:

  • Built-in OAuth Middleware: If you’re generating tokens via ASP.NET Identity’s OAuth server, the middleware handles expiry validation automatically. Configure it in your API’s Startup.cs:
    public void ConfigureAuth(IAppBuilder app)
    {
        var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new YourCustomOAuthProvider(PublicClientId),
            AccessTokenExpireTimeSpan = TimeSpan.FromHours(1),
            AllowInsecureHttp = false // Disable in production!
        };
        
        app.UseOAuthAuthorizationServer(oAuthOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
    
    When a token expires, the API will automatically return a 401 Unauthorized response.
  • Custom Authorization Filter: If you’re using a custom token format (like JWT), build a filter to check expiry manually. First, add the System.IdentityModel.Tokens.Jwt NuGet package, then create the filter:
    public class TokenExpiryValidationFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var authHeader = actionContext.Request.Headers.Authorization;
            
            if (authHeader == null || authHeader.Scheme != "Bearer")
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.Unauthorized, "Authorization header missing or invalid");
                return;
            }
            
            var token = authHeader.Parameter;
            var jwtHandler = new JwtSecurityTokenHandler();
            
            if (!jwtHandler.CanReadToken(token))
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, "Invalid token format");
                return;
            }
            
            var jwtToken = jwtHandler.ReadJwtToken(token);
            if (jwtToken.ValidTo < DateTime.UtcNow)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.Unauthorized, "Token has expired");
            }
            
            base.OnActionExecuting(actionContext);
        }
    }
    
    Apply it to your API controllers or actions like this:
    [TokenExpiryValidationFilter]
    public class SecureApiController : ApiController
    {
        // Your secure endpoints here
    }
    

Bonus: Handling Expired Tokens in MVC

When your MVC client gets a 401 from the API, trigger a token refresh flow: call your API’s token endpoint again to get a new token, update your stored token, and retry the original API request.


内容的提问来源于stack exchange,提问作者vishwakant singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:29:18