07 为 MVC 客户端刷新 Token


原文:https://www.yuque.com/yuejiangliu/dotnet/gbzs4g


07 为 MVC 客户端刷新 Token.mp4 (72.6 MB)

OpenID Connect 协议 构造 RefreshTokenRequest:

image.png

在 MVC Client 的 HomeController 中添加刷新 Token 的方法:

private async Task<string> RenewTokenAsync()
{
    var client = new HttpClient();
    var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000/");

    if (disco.IsError) throw new Exception(disco.Error);

    var refreshToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken);

    // Refresh Access Token
    var tokenResponse = await client.RequestRefreshTokenAsync(new RefreshTokenRequest
    {
        Address = disco.TokenEndpoint,
        ClientId = "mvc client",
        ClientSecret = "mvc secret",
        Scope = "api1 openid profile email phone address",
        GrantType = OpenIdConnectGrantTypes.RefreshToken,
        RefreshToken = refreshToken
    });

    if (tokenResponse.IsError) throw new Exception(tokenResponse.Error);

    var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResponse.ExpiresIn);

    var tokens = new[]
    {
        new AuthenticationToken
        {
            Name = OpenIdConnectParameterNames.IdToken,
            Value = tokenResponse.IdentityToken
        },
        new AuthenticationToken
        {
            Name = OpenIdConnectParameterNames.AccessToken,
            Value = tokenResponse.AccessToken
        },
        new AuthenticationToken
        {
            Name = OpenIdConnectParameterNames.RefreshToken,
            Value = tokenResponse.RefreshToken
        },
        new AuthenticationToken
        {
            Name = "expires_at",
            Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
        }
    };

    // 获取身份认证的结果,包含当前的 Principal 和 Properties
    var currentAuthenticateResult =
        await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

    // 更新 Cookie 里面的 Token
    currentAuthenticateResult.Properties.StoreTokens(tokens);

    // 登录
    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
        currentAuthenticateResult.Principal, currentAuthenticateResult.Properties);

    return tokenResponse.AccessToken;
}
Switching to Hybrid Flow and adding API Access back 中的代码。

相关