如何在 IdentityServer 4 中使用 'refresh_token'?

How to use 'refresh_token' in IdentityServer 4?

我在 IdentityServer 4 中使用 .net 核心。我有一个 Web api,以及一个访问 api 上安全端点的 MVC 应用程序。它的设置与 IdentityServer 快速入门非常相似:

https://github.com/IdentityServer/IdentityServer4.Samples/tree/release/Quickstarts/6_AspNetIdentity

我发现我的 access_tokens 即将到期,我想了解如何重新协商 refresh_tokens

以下面的代码为例(取自快速入门here):

public async Task<IActionResult> CallApiUsingUserAccessToken()
    {
        var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");

        var client = new HttpClient();
        client.SetBearerToken(accessToken);
        var content = await client.GetStringAsync("http://localhost:5001/identity");

        ViewBag.Json = JArray.Parse(content).ToString();
        return View("json");
    }

如果 access_token 已过期,它将失败并返回 401 响应。是否有使用 refresh_token 重新协商 access_token 的内置机制?

没有内置系统来刷新 access_token。但是,您可以使用 IdentityModel 包来请求带有 refresh_token.

的新 access_token

Client 有一个 属性 AllowOfflineAccess,您应该在 IdentityServer 中将其设置为 true。请注意,这 不适用于 implicit/client 凭据流。

  • 总是在调用受保护资源之前刷新access_token
  • 通过检查其生命周期来检查当前 access_token 是否即将过期,并请求具有 refresh_token(个人偏好)
  • 的新 access_token
  • 等待 API 到 return 401 并使用 refresh_token
  • 请求新的 access_token

在此代码之前,您可以检查 access_token 生命周期 and/or 在请求新 access_token

之前将此代码包装在服务中
    var discoveryResponse = await DiscoveryClient.GetAsync("IdentityServer url");
    if (discoveryResponse.IsError)
    {
        throw new Exception(discoveryResponse.Error);
    }
    
    var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "ClientId", "ClientSecret");
    // This will request a new access_token and a new refresh token.
    var tokenResponse = await tokenClient.RequestRefreshTokenAsync(await httpContext.Authentication.GetTokenAsync("refresh_token"));
    
    if (tokenResponse.IsError)
    {
        // Handle error.
    }
    
    var oldIdToken = await httpContext.Authentication.GetTokenAsync("id_token");
    
    var tokens = new List<AuthenticationToken>
    {
        new AuthenticationToken
        {
            Name = OpenIdConnectParameterNames.IdToken,
            Value = oldIdToken
        },
        new AuthenticationToken
        {
            Name = OpenIdConnectParameterNames.AccessToken,
            Value = tokenResult.AccessToken
        },
        new AuthenticationToken
        {
            Name = OpenIdConnectParameterNames.RefreshToken,
            Value = tokenResult.RefreshToken
        }
    };
    
    var expiresAt = DateTime.UtcNow.AddSeconds(tokenResult.ExpiresIn);
    tokens.Add(new AuthenticationToken
    {
        Name = "expires_at",
        Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
    });
    
    // Sign in the user with a new refresh_token and new access_token.
    var info = await httpContext.Authentication.GetAuthenticateInfoAsync("Cookies");
    info.Properties.StoreTokens(tokens);
    await httpContext.Authentication.SignInAsync("Cookies", info.Principal, info.Properties);

摘自并稍作修改:Source