ASP MVC OAuth项目:AccessToken设14天过期却实际1天失效
嘿,我仔细看了你的配置和返回的token信息,首先有个有意思的点:你拿到的token里expires_in是1209599秒,这其实就是14天的秒数(14×24×3600=1209600,差1秒是计算时的正常误差),而且.expires字段也显示到6月1日,和你配置的14天完全吻合。那为什么你会觉得实际1天就过期了?大概率是代码里有其他地方偷偷覆盖了token的过期时间,或者你把access token和cookie的过期搞混了,咱们一步步排查:
首先检查你的ApplicationOAuthProvider类
这是最常见的问题点!默认的ASP.NET OAuth模板里,GrantResourceOwnerCredentials方法如果手动设置了token的过期时间,会直接覆盖你在Startup.Auth里的全局配置。你去看看这个方法里有没有类似这样的代码:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { // ... 你的用户验证逻辑 var identity = new ClaimsIdentity(context.Options.AuthenticationType); // ... 添加用户声明 var props = new AuthenticationProperties(new Dictionary<string, string> { { "userName", context.UserName }, { "Id", user.Id } }); // 重点看这里!如果有这行,直接把过期时间改成1天了! // props.ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); }
如果真的有手动设置props.ExpiresUtc的代码,把它删掉就行,这样token就会继承你在OAuthOptions里配置的14天过期时间。
确认是不是混淆了AccessToken和Cookie的过期
你在Startup.Auth里同时启用了Cookie认证:
app.UseCookieAuthentication(new CookieAuthenticationOptions());
如果你的前端同时依赖cookie和bearer token,可能是cookie先过期了(默认cookie的过期时间比较短),让你误以为是access token失效。你可以单独测试:直接用拿到的access token通过Postman调用API,看是不是真的1天后就返回401,还是能正常访问到第14天。
检查有没有其他拦截逻辑修改token
比如有没有自定义的中间件,或者在OAuthProvider的其他方法里修改了token属性。你可以在ApplicationOAuthProvider里加个调试方法,确认最终生成的token过期时间是否正确:
public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context) { // 输出过期时间到调试窗口,看看是不是14天后 System.Diagnostics.Debug.WriteLine($"Token expires at: {context.Properties.ExpiresUtc}"); return base.TokenEndpointResponse(context); }
最后验证一下
重新生成token后,把它存下来,分别在1天后、13天后调用API,观察返回结果。如果1天后还能正常访问,那说明之前的问题是其他因素导致的,不是access token本身的过期时间配置错了。
内容的提问来源于stack exchange,提问作者William

