如何使用 .NET Core 使用 UTC 时间验证 JWT

Dev*_*lch 6 c# datetime jwt .net-core

目前我正在使用 JWT-Bearer-Authentication 对 ASP.NET-Core WebApi 进行编程。

为了使 API 可从不同的时区访问,我使用以下模式将JWT 中的字段nbf(notBefore) 和exp(expires) 设置为 UTC 时间戳:

var utcNow = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);

...

var tokenOptions = new JwtSecurityToken(
                notBefore: utcNow,
                expires: utcNow.AddSeconds(3600),
            );
...
Run Code Online (Sandbox Code Playgroud)

对于令牌生成,一切都很好,nbf并且exp包含代表当前 UTC 时间的 UNIX 时间戳。

但是在进行令牌验证时,一切都在 5 分钟(我的时钟偏差设置)内有效,然后我只能从 API 获得 401,因为令牌验证是使用我在德国的当前时区完成的。

有没有办法在 .NET-Core 中设置 JwtAuthentication-Middleware 以使用 UTC-Time 进行令牌验证?或者有没有其他方法可以解决这个问题?

Ser*_*gan 8

要获得更完整的答案,请在您的Startup.cs

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                // ...
                ValidateLifetime = true,
                LifetimeValidator = (DateTime? notBefore, DateTime? expires, SecurityToken securityToken, 
                                     TokenValidationParameters validationParameters) => 
                {
                    return notBefore <= DateTime.UtcNow &&
                           expires > DateTime.UtcNow;
                }
            };
        });
Run Code Online (Sandbox Code Playgroud)

  • 不,这不准确...除非特别重写,否则默认设置为 5 分钟。/sf/answers/3860899801/ (3认同)

Sai*_*uti 3

一种解决方案是在没有过期时间的情况下验证令牌。即使令牌已过期,这也会返回有效的令牌。然后在您的代码中手动检查令牌过期时间。以下是代码片段:

var validationParameters = new TokenValidationParameters()
{
   RequireExpirationTime = false,  // we can check manually
   ValidateIssuer = true,
   ValidateAudience = true,

   .
   .
   IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
};
            
Run Code Online (Sandbox Code Playgroud)

然后,当验证令牌时,使用以下命令检查过期时间:

public bool IsExpired(DateTime now)
{
    return JwtSecurityToken.ValidTo < Date.UtcNow;
}
Run Code Online (Sandbox Code Playgroud)

我希望这个答案会对某人有所帮助。