【问题标题】:Is there a minimum expiration time for JwtSecurityToken?JwtSecurityToken 有最短过期时间吗?
【发布时间】:2018-05-25 01:44:03
【问题描述】:

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

大约在 13:15 时,我再次运行验证,它抛出了异常,正如预期的那样。

令牌是否有最短过期时间?


创建令牌:

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

验证令牌:

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;
}

【问题讨论】:

  • 您是说问题中的第二个 13:07 是 13:12?
  • @JonSkeet 抱歉。
  • 没问题 - 只是不想让其他人感到困惑 :)
  • 不完全是重复的,但我相当肯定,这将解决问题 - stackoverflow.com/a/29456969/6804888

标签: c# xamarin.android jwt token


【解决方案1】:

这是由于 ClockSkew 令牌验证参数,它允许提供一个缓冲区来解决发出 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 
            };
        });

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 2021-07-05
    • 2017-02-05
    • 1970-01-01
    • 2021-04-07
    • 2013-01-16
    • 1970-01-01
    • 2017-12-29
    相关资源
    最近更新 更多