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

.NET Identity Bearer Token 为不同客户端动态设置过期时间

解决方案

要在同一个IdentityConstants.BearerScheme下给不同客户端设置动态Token过期时间,核心是利用AuthenticationProperties传递自定义过期参数,替换默认的PasswordSignInAsync调用方式即可,步骤如下:

  1. 修改登录方法,传入自定义过期属性
    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;
  1. 确保全局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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 17:30:09