c# - JwtSecurityToken 是否有最短到期时间?

标签 c# xamarin.android jwt token

在 token 验证中,我检查了 token 的生命周期,它是13:07:10。当我运行验证时,时间是 13:12,验证成功。 为什么?

当大约是 13:15 时,我再次运行验证,结果如预期的那样抛出了异常。

token 是否有最短到期时间?


创建 token :

var token = new JwtSecurityToken(
    issuer: token_issuer,
    audience: token_audience,
    claims: claims,
    expires: DateTime.Now.AddSeconds(5),                
    signingCredentials: creds
);

验证 token :

private static bool ValidateToken(string token)
{
    try
    {
        TokenValidationParameters validationParameters = new TokenValidationParameters
        {
            IssuerSigningKey = new SymmetricSecurityKey(token_salt),
            ValidAudience = token_audience,
            ValidIssuer = token_issuer,
            RequireExpirationTime = true
        };

        ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(token_last, validationParameters, out SecurityToken validatedToken);

        return true;
    }
    catch(SecurityTokenExpiredException ex)
    {

    }

    return false;
}

最佳答案

这是由于 ClockSkew token 验证参数,它允许提供一个缓冲区来解决发布 JWT 的服务器和验证它的服务器之间的时钟差异。

在 .NET Core/5+ 中,您可以在 Startup 的 JwtBearer 配置中的 TokenValidationParameters 对象中更改其值,如下所示。其默认值为 300 秒或 5 分钟。

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://some-jwt-token-issuer.com";
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                // Set the below to eliminate the skew
                ClockSkew = TimeSpan.Zero 
            };
        });

关于c# - JwtSecurityToken 是否有最短到期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47754556/

相关文章:

c# - 从 DataGrid 中删除无效行后,我无法更新行

c# - WinRT 中 TextBlock 的外发光效果

c# - 如何获取具有自定义属性的类的每个属性然后在下拉列表中显示它们?

android - 如何在 Android 中创建此布局

c# - 拉动刷新在使用 Xamarin Forms 构建的 Android 中的 ListView 上不起作用

c# - 在 Xamarin 浏览器控件中访问 html 响应内容

c# - JwtSecurityToken 返回错误的过期时间

python - 使用 FastAPI 和 Swagger 刷新 token

c# - 在迭代 DbDataReader 之前处理 DbCommand 是否可以

python - JWT: 'module' 对象没有属性 'encode'