【问题标题】:JwtSecurityToken expiration date is two hours apartJwtSecurityToken 过期日期相隔两个小时
【发布时间】:2018-04-27 22:44:51
【问题描述】:

在我的 .net core api 应用程序中,我使用:

var dt = DateTime.Now.AddMinutes(60); // time is 2018-04-27 14:49:00

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var claims = new[]
              {
                 new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                 new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                 new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
              };

var token = new JwtSecurityToken(
        _config["Tokens:Issuer"], 
        _config["Tokens:Audience"], 
        claims,
        expires: dt,
        signingCredentials: creds);

token.ValidTo 显示为2018-04-27 12:49:00 ...

为什么?

【问题讨论】:

    标签: api jwt


    【解决方案1】:

    这是因为不同的时区。您的时区可能是 UTC+2,而您的变量 dt 包含本地时间。

    JwtSecurityToken.ValidTo 是一个 DateTime 值,其中包含 UTC 时间。生成的 JWT 将为您提供基于 Unix 纪元时间的值 (exp claim),以秒为单位 1970-01-01 00:00 UTC。 在您的情况下,exp 将是

    1524833340

    等于

    2018-04-27 12:49:00 UTC(UTC+2 为 14:49)

    您可以查看here,JWT 框架知道如何处理它,与时区无关。

    行为是正确的,您无需更改任何内容。

    【讨论】:

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