目前我正在使用 JWT-Bearer-Authentication 编写 ASP.NET-Core WebApi。
为了使 API 可以从不同时区访问,我使用以下模式来设置字段nbf
(不是之前)和exp
(过期)在我的 JWT 内到 UTC 时间戳:
var utcNow = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
...
var tokenOptions = new JwtSecurityToken(
notBefore: utcNow,
expires: utcNow.AddSeconds(3600),
);
...
对于代币生成来说,一切都运行良好,nbf
and exp
包含表示当前 UTC 时间的 UNIX 时间戳。
但是在进行令牌验证时,一切都有效 5 分钟(我的时钟偏差设置),然后我只从 API 得到 401,因为令牌验证是使用我在德国当前的时区完成的。
有没有办法在 .NET-Core 中设置 JwtAuthentication-Middleware 以使用 UTC 时间进行令牌验证?或者还有其他方法可以解决这个问题吗?
如需更完整的答案,请在您的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;
}
};
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)