问题描述
我正在尝试通过.NET Core 2.1中的刷新令牌和JWT实现基于令牌的身份验证.
I am trying to implement Token Based Authentication through refresh tokens and JWT in .NET Core 2.1.
这是我实现JWT令牌的方式:
This is how I am implementing the JWT Token:
Startup.cs
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
};
我在响应中得到他正确的值.
I am getting he correct values in Response.
但是过了一会儿,我在邮递员中设置了相同的令牌进行授权,并且该令牌有效.如果令牌已过期,则不应过期.
But after a minute I set the same token for authorization in Postman and it works.If the token has expired it shouldn't.
我正在使用承载令牌作为身份验证.
I am using bearer tokens as authentication.
我做错了什么?需要指导.
What am I doing wrong? Need direction.
推荐答案
有一个称为ClockSkew
的令牌验证参数,它是获取或设置验证时间时要应用的时钟偏斜的方法. ClockSkew
的默认值为5分钟.也就是说,如果您尚未设置令牌,则令牌在5分钟内仍然有效.
There is one token validation parameter called ClockSkew
, it is gets or sets the clock skew to apply when validating a time. The default value of ClockSkew
is 5 minutes. That means if you haven't set it, your token will be still valid up to 5 minutes.
如果您想在正确的时间使令牌到期;您需要将ClockSkew
设置为零,如下所示,
If you want to expiry your token on the exact time; you'd need to set ClockSkew
to zero as follows,
options.TokenValidationParameters = new TokenValidationParameters()
{
//other settings
ClockSkew = TimeSpan.Zero
};
另一种方法是,创建自定义AuthorizationFilter
并手动进行检查.
Another way, create custom AuthorizationFilter
and check it manually.
var principal = ApiTokenHelper.GetPrincipalFromToken(token);
var expClaim = principal.Claims.First(x => x.Type == "exp").Value;
var tokenExpiryTime = Convert.ToDouble(expClaim).UnixTimeStampToDateTime();
if (tokenExpiryTime < DateTime.UtcNow)
{
//return token expried
}
在这里,GetPrincipalFromToken
是ApiTokenHelper
类的自定义方法,它将返回您在发行令牌时存储的ClaimsPrincipal
值.
Here, GetPrincipalFromToken
is a custom method of ApiTokenHelper
class, and it will return ClaimsPrincipal
value that you've stored while issuing a token.
这篇关于JWT令牌到期时间失败的.net核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!