【发布时间】:2019-08-04 14:45:13
【问题描述】:
我正在尝试通过 .NET Core 2.1 中的刷新令牌和 JWT 来实现基于令牌的身份验证。
这就是我实现 JWT 令牌的方式:
Startup.cs
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = Configuration["Jwt:Site"],
ValidIssuer = Configuration["Jwt:Site"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SigningKey"]))
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
令牌生成:
var jwt = new JwtSecurityToken(
issuer: _configuration["Jwt:Site"],
audience: _configuration["Jwt:Site"],
expires: DateTime.UtcNow.AddMinutes(1),
signingCredentials: new SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256)
);
return new TokenReturnViewModel()
{
token = new JwtSecurityTokenHandler().WriteToken(jwt),
expiration = jwt.ValidTo,
currentTime = DateTime.UtcNow
};
我在 Response 中得到了正确的值。
但是一分钟后,我在 Postman 中设置了相同的授权令牌,它就可以工作了。 如果令牌已过期,则不应。
我使用不记名令牌作为身份验证。
我做错了什么?需要方向。
【问题讨论】:
-
您是否检查了本地日期时间值而不是 UTC 值?
-
我有当地时间给出了以下问题: - expires 自动采用 UTC 时间,无论我使用什么。
-
@AbhilashGopalakrishna 始终使用带有令牌的 UTC 时间,而不是本地时间
标签: asp.net-web-api .net-core jwt access-token refresh-token