目前我正在使用 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),
);
...
对于 token 生成,一切都很好,nbf
和 exp
包含一个代表当前 UTC 时间的 UNIX 时间戳。
但是在进行 token 验证时,一切都工作 5 分钟(我的时钟偏差设置),然后我只从 API 获得 401,因为 token 验证是在我当前的德国时区完成的。
有没有办法在 .NET-Core 中设置 JwtAuthentication-Middleware 以使用 UTC 时间进行 token 验证?或者还有其他方法可以解决这个问题吗?
最佳答案
要获得更完整的答案,请在您的 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;
}
};
});
关于c# - 如何使用 .NET Core 使用 UTC 时间验证 JWT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55341414/