【发布时间】:2021-06-04 04:14:55
【问题描述】:
我已经在asp.net core 3.1中创建了项目,并且可以成功授权。
问题是我想增加 JWT 令牌的生命周期,我尝试了所有可能的方法,但仍然无法获得适当的帮助或回答我正在寻找的内容。
下面是startup.cs
中的代码services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
RequireExpirationTime = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
//ClockSkew = TimeSpan.Zero,
ValidIssuer = _configuration.GetSection("BaseUrl").Value,
ValidAudience = _configuration.GetSection("BaseUrl").Value,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("IssuerSigningKey").Value)),
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
context.Response.OnStarting(() =>
{
context.Response.StatusCode = 499;
return Task.CompletedTask;
});
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
以下是生成 JWT 令牌的代码,
string GeneratJwtToken()
{
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("IssuerSigningKey").Value));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var claims = new[] { new Claim("Source", "PmpMobileApp") };
var tokeOptions = new JwtSecurityToken(
issuer: _configuration.GetSection("BaseUrl").Value,
audience: _configuration.GetSection("BaseUrl").Value,
claims,
expires: DateTime.Now.AddSeconds(20),
signingCredentials: signinCredentials
);
return new JwtSecurityTokenHandler().WriteToken(tokeOptions);
}
我见过刷新令牌的概念,但是对于刷新令牌,它应该从中间件返回 401 未经授权的错误,然后我可以调用刷新令牌 api。但在此它会返回 200 登录页面成功。
另外注意到,令牌在本地开发环境中不会过期,但在生产环境中会在几分钟内过期。
注意:- 在网络和移动设备上使用相同的项目。
【问题讨论】:
-
由于令牌内容是可读的,因为它只是 base64url 编码,您应该使用例如调试令牌jwt.io,并检查
exp属性的值。如果将鼠标悬停在它上面,它会显示人类可读的日期时间。ValidateLifetime选项基本上只是检查这个给定的日期时间是否已经过去;因此,如果exp日期时间包含预期值,则令牌不应在几分钟后被视为过期(问题可能是其他问题)。
标签: asp.net-core authentication asp.net-web-api jwt authorization