.NET 8 Identity Framework Web API 如何控制Token过期时间
修改ASP.NET Core 8 Identity API端点的Token过期时间
你的问题核心是:AddIdentityApiEndpoints内部通过AddBearerToken配置了默认3600秒的Token过期时间,需要覆盖这个默认值且不修改内置的/account/login端点逻辑。
解决方案:配置BearerTokenOptions
AddIdentityApiEndpoints使用IdentityConstants.BearerScheme作为Bearer Token的认证方案标识,我们可以通过针对该方案配置BearerTokenOptions来修改Token生命周期。
具体实现代码
在你的Program.cs中,添加以下配置(放在AddIdentityApiEndpoints调用之后即可):
//This will add the API endpoints for the Identity DB builder.Services .AddIdentityApiEndpoints<DemoUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<DemoIdentityRoles>() .AddEntityFrameworkStores<DemoSecurityDbContext>(); // 配置Bearer Token过期时间 builder.Services.Configure<BearerTokenOptions>(IdentityConstants.BearerScheme, options => { // 设置AccessToken过期时间,示例为30分钟(1800秒) options.TokenLifetime = TimeSpan.FromMinutes(30); // 可选:设置RefreshToken过期时间,示例为7天 options.RefreshTokenLifetime = TimeSpan.FromDays(7); });
说明
- 该配置直接作用于内置的
/account/login端点生成的Token,无需自定义登录逻辑或覆盖端点 TokenLifetime控制AccessToken的有效期,对应返回结果中的expiresIn字段RefreshTokenLifetime控制RefreshToken的有效期,若不需要可省略该配置
内容的提问来源于stack exchange,提问作者Gesuele Russello
相关产品推荐
相关产品推荐

