如何在ASP.NET Core 8 Minimal API中配置IdentityApi的AccessToken有效期
问题
我刚着手开发一个新的ASP.NET Core 8 Minimal API,正在尝试使用身份认证相关的新特性。我通过以下AuthInstaller类注册认证服务:
internal static class AuthInstaller { internal static IServiceCollection InstallAuth(this IServiceCollection services) { services .AddAuthorization() .AddIdentityApiEndpoints<ApplicationUser>() .AddEntityFrameworkStores<DatabaseContext>(); return services; } }
随后在端点安装类中,我调用MapIdentityApi<ApplicationUser>()来映射身份认证端点。目前所有功能都能正常运行,但AccessToken的有效期被设置为3600秒。我花了很多时间研究如何配置该有效期,请问有没有无需编写自定义Bearer令牌创建逻辑的快速配置方法?我查阅了微软文档,但未找到有用信息。
回答
你可以通过配置IdentityOptions直接调整AccessToken的有效期,无需自定义令牌生成逻辑。具体做法是在注册身份服务时,添加对IdentityOptions的配置:
修改你的AuthInstaller类,加入Configure<IdentityOptions>的调用,调整TokenOptions.AccessTokenLifetime属性:
internal static class AuthInstaller { internal static IServiceCollection InstallAuth(this IServiceCollection services) { services .AddAuthorization() .AddIdentityApiEndpoints<ApplicationUser>() .AddEntityFrameworkStores<DatabaseContext>(); // 配置AccessToken有效期为2小时(7200秒),可根据需求自行调整时长 services.Configure<IdentityOptions>(options => { options.Tokens.AccessTokenLifetime = TimeSpan.FromHours(2); }); return services; } }
这个方法直接复用ASP.NET Core Identity内置的配置项,完全适配AddIdentityApiEndpoints提供的默认端点,不需要额外编写自定义Bearer令牌逻辑。
内容的提问来源于stack exchange,提问作者bartusko_
相关产品推荐
相关产品推荐

