c# - 忽略某些路由上的过期令牌
问题描述
使用 JWT 令牌,我正在为我的 .NET Core API 进行身份验证。我想知道当用户请求某个路由(例如“/refresh”)以刷新过期令牌时,我是否可以告诉我的 API 忽略令牌的到期。我知道可以通过 POST 请求提供令牌来解决它,但是当我只想识别调用用户时,我希望能够忽略令牌的到期。
我的代码如下所示。目前它适用于 POST 请求,但我希望能够通过标头提供过期令牌。
[AllowAnonymous]
[HttpPost("refresh")]
public async Task<IActionResult> Refresh(RefreshRequest refreshRequest)
{
// Validate refresh token
if (!_tokenService.RefreshTokenValid(refreshRequest.Refresh_Token)) {
return BadRequest("The request token is not a valid token.");
}
var tokenHandler = new JwtSecurityTokenHandler();
// Validate actual token
if (!tokenHandler.CanReadToken(refreshRequest.Token)) {
return BadRequest("The JWT token is not a valid token.");
}
// Get the user from the JWT token
var userId = _tokenService.GetUserIdFromtoken(refreshRequest.Token);
var repoUser = await _repo.GetUserById(userId);
// Map the user, generate a token and send response
var newToken = _tokenService.GenerateRefreshedJwtToken(repoUser);
var tokenUser = _mapper.Map(repoUser, new AuthRefreshedTokenUser(newToken));
return Ok(tokenUser);
}
解决方案
一种简单的方法是创建另一个身份验证模式并设置为不验证令牌的生命周期:
.AddJwtBearer(options =>
{
...
options.TokenValidationParameters.ValidateLifetime = false;
....
});
[Authorize(AuthenticationSchemes = "schemeName")]
并在特定控制器/操作上应用该身份验证方案 。
推荐阅读
- performance - 使用 clone_from_slice() 而不是 copy_from_slice() 的性能损失?
- angular - Angular Material mat-select 设置值后不刷新
- python - pymysql.err.OperationalError - 查询期间丢失与 MySQL 服务器的连接
- css - Chrome浏览器中的背景颜色奇怪但Edge中没有
- azure-logic-apps - 如何在 LogicApp 中为对象使用评估属性?
- java - java编译器是怎么看源码的?
- javascript - 将 HTML 添加到条形图的标签 - 图表 js
- visual-studio - XUnit - VS2019 - 具有 inlinedata 的理论在分组中不显示 DisplayName
- python - 给定直方图计算 PDF
- java - 无法从 android studio 中的片段启动另一个活动