【问题标题】:How to implement JWT Refresh Tokens in asp.net core web api (no 3rd party)?如何在 asp.net core web api(无第三方)中实现 JWT 刷新令牌?
【发布时间】:2017-04-18 08:28:56
【问题描述】:

我正在使用使用 JWT 的 asp.net 核心实现 Web api。我没有使用第三方解决方案,例如我正在尝试学习的 IdentityServer4。

我已经让 JWT 配置正常工作,但是对于如何在 JWT 过期时实现刷新令牌感到困惑。

下面是我在 startup.cs 中的 Configure 方法中的一些示例代码。

app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
    AuthenticationScheme = "Jwt",
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = new TokenValidationParameters()
    {
        ValidAudience = Configuration["Tokens:Audience"],
        ValidIssuer = Configuration["Tokens:Issuer"],
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])),
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    }
});

以下是用于生成 JWT 的 Controller 方法。出于测试目的,我已将过期时间设置为 30 秒。

    [Route("Token")]
    [HttpPost]
    public async Task<IActionResult> CreateToken([FromBody] CredentialViewModel model)
    {
        try
        {
            var user = await _userManager.FindByNameAsync(model.Username);

            if (user != null)
            {
                if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)
                {
                    var userClaims = await _userManager.GetClaimsAsync(user);

                    var claims = new[]
                    {
                        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                    }.Union(userClaims);

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwt.Key));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken(
                            issuer: _jwt.Issuer,
                            audience: _jwt.Audience,
                            claims: claims,
                            expires: DateTime.UtcNow.AddSeconds(30),
                            signingCredentials: creds
                        );

                    return Ok(new
                    {
                        access_token = new JwtSecurityTokenHandler().WriteToken(token),
                        expiration = token.ValidTo
                    });
                }
            }
        }
        catch (Exception)
        {

        }

        return BadRequest("Failed to generate token.");
    }

非常感谢您的指导。

【问题讨论】:

  • 您发布的代码仅与验证访问令牌相关,与刷新令牌无关。你能分享你生成访问令牌的代码吗?
  • 当然,我已经添加了用于生成 JWT 的代码。

标签: c# asp.net asp.net-web-api


【解决方案1】:

首先,您需要生成一个刷新令牌并将其保存在某个地方。这是因为您希望能够在需要时使其无效。如果您要遵循与访问令牌相同的模式 - 所有数据都包含在令牌中 - 最终落入坏人手中的令牌可用于在刷新令牌的生命周期内生成新的访问令牌,这可能会很长。

那么你到底需要坚持什么?

您需要某种不易猜到的唯一标识符,GUID 就可以了。您还需要数据才能发布新的访问令牌,很可能是用户名。拥有用户名后,您可以跳过 VerifyHashedPassword(...) 部分,但其余部分只需遵循相同的逻辑即可。

要获取刷新令牌,您通常使用范围“offline_access”,这是您在发出令牌请求时在模型 (CredentialViewModel) 中提供的内容。与普通的访问令牌请求不同,您不需要提供用户名和密码,而是提供刷新令牌。获取带有刷新令牌的请求时,您会查找持久标识符并为找到的用户发出令牌。

以下是快乐路径的伪代码:

[Route("Token")]
[HttpPost]
public async Task<IActionResult> CreateToken([FromBody] CredentialViewModel model)
{
    if (model.GrantType is "refresh_token")
    {
        // Lookup which user is tied to model.RefreshToken
        // Generate access token from the username (no password check required)
        // Return the token (access + expiration)
    }
    else if (model.GrantType is "password")
    {
        if (model.Scopes contains "offline_access")
        {
            // Generate access token
            // Generate refresh token (random GUID + model.username)
            // Persist refresh token
            // Return the complete token (access + refresh + expiration)
        }
        else
        {
            // Generate access token
            // Return the token (access + expiration)
        }
    }
}

【讨论】:

    猜你喜欢
    • 2018-03-30
    • 2020-11-04
    • 1970-01-01
    • 2019-08-03
    • 2021-03-11
    • 2019-08-16
    • 2019-05-08
    • 2021-07-23
    • 2017-05-27
    相关资源
    最近更新 更多