【问题标题】:Can't restrict the lifetime of a JWT token in .NET Core无法限制 .NET Core 中 JWT 令牌的生命周期
【发布时间】:2019-12-01 17:03:56
【问题描述】:

我的同事使用下面的代码生成了一个令牌。

byte[] secret = Encoding.UTF8.GetBytes("hakunana_matata_kurva_garbata");
SecurityKey key = new SymmetricSecurityKey(secret);
SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
JwtSecurityToken jwt = new JwtSecurityToken(
  "https://localhost:44385",
  "https://localhost:44385",
  new Claim[] { },
  DateTime.Now,
  DateTime.Now.AddMinutes(1),
  credentials);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);

我期望它执行的方式是允许访问 6o 秒然后停止工作。这似乎没有发生,并且无论如何都会调用安全方法(它不适用于错误的令牌和没有令牌的请求)。一段时间后(不确定多长时间)令牌停止工作(我猜它已经过期了)。

我还检查了 JWT 页面中的令牌。让我感到奇怪的是 not beforeexpiry 的两行。和预期的一样,它们之间的差异似乎是 60 秒。

{
  "nbf": 1563895482,
  "exp": 1563895542,
  "iss": "https://localhost:44385",
  "aud": "https://localhost:44385"
}

我确保安全配置要求验证到期日期。

TokenValidationParameters parameters = new TokenValidationParameters
{
  ValidateIssuerSigningKey = true,
  ValidateLifetime = true,
  ValidateAudience = false,
  ValidateIssuer = false,
  IssuerSigningKey = new SymmetricSecurityKey(hakuna_whatever)
};

我在这里错过了什么?

【问题讨论】:

  • 什么是“安全”方法?我认为我们可能需要查看更多您的 JWT 工作流程才能在此处尝试回答。请注意,理想情况下,JWT 旨在成为一种完全无状态维护会话状态的方式。也就是说,在某些情况下,您的 .NET 应用程序只需要检查传入 JWT 的声明即可决定如何处理该请求。
  • @TimBiegeleisen 您是否暗示检查过期和禁止之前与安全性无关,我应该只关注索赔?
  • 不确定您的意思,但exp(到期)声明。
  • @TimBiegeleisen 啊哈,是我不知道索赔的定义。我认为声明是作为 Claim[] 类型列表的成员显式传递的那些事物之一。现在我想起来了,expnbf 等也是声明是完全有道理的,但它们是如此基本,它们是由专用变量而不是一般变量传递的列表。幸运的是,有人猜测并成功了 - 这是及时的偏差。

标签: c# authentication asp.net-core .net-core jwt


【解决方案1】:

问题是ClockSkew,默认为 5 分钟(参见例如this post)。指定TokenValidationParameters时设置为TimeSpan.Zero

TokenValidationParameters parameters = new TokenValidationParameters
{
    // [...]
    ClockSkew = TimeSpan.Zero
};

【讨论】:

    猜你喜欢
    • 2018-12-23
    • 2020-11-06
    • 2021-06-04
    • 2019-06-17
    • 2019-05-11
    • 2019-01-21
    • 2018-10-07
    • 2018-07-18
    • 2021-08-01
    相关资源
    最近更新 更多