首页 > 解决方案 > 忽略某些路由上的过期令牌

问题描述

使用 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);
}

标签: c#apiauthenticationasp.net-corejwt

解决方案


一种简单的方法是创建另一个身份验证模式并设置为不验证令牌的生命周期:

.AddJwtBearer(options =>
{
    ...
    options.TokenValidationParameters.ValidateLifetime = false;
    ....

});

[Authorize(AuthenticationSchemes = "schemeName")]并在特定控制器/操作上应用该身份验证方案 。


推荐阅读