.NET Identity Bearer Token 为不同客户端动态设置过期时间
解决方案
要在同一个IdentityConstants.BearerScheme下给不同客户端设置动态Token过期时间,核心是利用AuthenticationProperties传递自定义过期参数,替换默认的PasswordSignInAsync调用方式即可,步骤如下:
- 修改登录方法,传入自定义过期属性
PasswordSignInAsync有重载版本支持接收AuthenticationProperties参数,我们可以在这个对象里指定Token的过期时间,替代全局配置的固定值。
Web端登录修改后代码:
_signInManager.AuthenticationScheme = IdentityConstants.BearerScheme; // 配置Web端Token过期为1天 var authProps = new AuthenticationProperties { ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1), IsPersistent = false // 对应原代码中的isPersistent参数 }; var result = await _signInManager.PasswordSignInAsync( loginForVisionRequest.Email, loginForVisionRequest.Password, authProps, lockoutOnFailure: true ); if (!result.Succeeded) { return TypedResults.Problem("Unauthorized", statusCode: 401); } return TypedResults.Empty;
移动端登录修改后代码:
_signInManager.AuthenticationScheme = IdentityConstants.BearerScheme; // 配置移动端Token过期为14天 var authProps = new AuthenticationProperties { ExpiresUtc = DateTimeOffset.UtcNow.AddDays(14), IsPersistent = false }; var result = await _signInManager.PasswordSignInAsync( loginForVisionRequest.Email, loginForVisionRequest.Password, authProps, lockoutOnFailure: true ); if (!result.Succeeded) { return TypedResults.Problem("Unauthorized", statusCode: 401); } return TypedResults.Empty;
- 确保全局Bearer配置不固定过期时间
在Program.cs(或Startup.cs)中配置Bearer认证时,不要硬编码TokenLifetime,否则会覆盖我们传入的自定义过期值:
builder.Services.AddAuthentication(IdentityConstants.BearerScheme) .AddBearerToken(options => { // 移除或注释掉固定TokenLifetime的配置 // options.TokenLifetime = TimeSpan.FromDays(1); });
原理说明
AuthenticationProperties中的ExpiresUtc属性会被Identity的Bearer令牌生成逻辑优先读取,替代全局配置的过期时间,这样就能在不同登录方法中动态设置不同的Token有效期,完全符合你要求的同Scheme、非JWT的场景。
内容的提问来源于stack exchange,提问作者osmanc
相关产品推荐
相关产品推荐

