【问题标题】:Renew access token with every request每次请求都更新访问令牌
【发布时间】:2018-09-20 09:21:43
【问题描述】:

我有一个登录方法,它给了我访问和刷新令牌。

[HttpGet]
[AllowAnonymous]
public IActionResult Login()
{
    var claims = new Claim[]
    {
        new Claim(ClaimTypes.Role, "Administrator")
    };
    var now = DateTime.UtcNow;
    var signingCredentials = new SigningCredentials(
        new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.configuration["Key"])), SecurityAlgorithms.HmacSha256);

    var accessToken = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
        claims: claims,
        notBefore: now,
        expires: now.AddMinutes(10),
        signingCredentials: signingCredentials));

    var refreshToken = new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
        notBefore: now,
        expires: now.AddYears(2),
        signingCredentials: signingCredentials));

    return Ok(new JwtToken
    {
        AccessToken = accessToken,
        RefreshToken = refreshToken
    }); 
}

我将访问令牌与 Postman 一起使用。在标题中:

承载 eyJhbGciOiJIUzI1...

但 10 分钟后我无法使用 API,因为访问令牌被拒绝。如何在每次向 API 发出请求时(在这 10 分钟内)更新访问令牌?

【问题讨论】:

  • 如果您在每个请求上刷新令牌,您还需要在每个邮递员请求上更改它?
  • 您使用刷新令牌来更新访问令牌,并且不需要在您的访问令牌有效的10分钟内,而是在刷新令牌有效的时间内。请参阅this answer 以更好地了解它。我也推荐。在该答案中,您还将找到指向一个好的教程 esp 的链接。对于 C#/ASP.net。

标签: c# asp.net-core jwt


【解决方案1】:

您可以使用令牌的到期时间设置变量或 cookie,然后发出的每个请求都需要检查此到期时间是否过去。如果是,您应该能够使用刷新令牌来获取新的访问令牌。

这将确保您不会为每个请求获取令牌,而只会在令牌过期时获得。

【讨论】:

  • 好主意,但我有同样的问题:如何更新访问令牌。如果授权失败,我调用API获取新令牌?
猜你喜欢
  • 2020-07-26
  • 2016-04-01
  • 2020-06-01
  • 2020-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多