xamarin.forms - 如何使用刷新 token 通过 Xamarin.Forms 客户端从身份服务器 4 获取新的访问 token

标签 xamarin.forms identityserver4 refresh-token

如何使用refresh_token从Xamarin.Forms客户端中的身份服务器获取新的访问 token ?

我按照教程https://sinclairinat0r.com/2018/12/09/secure-data-access-with-identityserver4-and-xamarin-forms进行操作并创建了 Xamarin Forms 移动应用程序,并在 IS4 上进行了身份验证。我将访问 token 的生命周期设置为几分钟。访问 token 过期后(如异常(exception)),应用程序将无法再访问授权端点。我有一个刷新 token ,但我不知道如何使用它从身份服务器获取新的访问 token 。

is4 配置中指定的客户端:

            new Client()
            {
                ClientId = "xamarin-client",
                ClientName = "Xamarin client",
                AllowedGrantTypes = { "authorization_code" },
                AllowedScopes = {"openid", "profile", "values-api" },
                AllowAccessTokensViaBrowser = true,
                AllowOfflineAccess = true,
                AlwaysIncludeUserClaimsInIdToken = true,
                RequirePkce = true,
                RequireClientSecret = false,
                RedirectUris = { "https://iglooidentityserver.azurewebsites.net/grants" },

                AccessTokenLifetime = 180,
            }

我使用过的身份验证器:

        var oAuth = new OAuth2AuthenticatorEx(
            "xamarin-client",
            "offline_access values-api",
            new Uri("https://iglooidentityserver.azurewebsites.net/connect/authorize"),
            new Uri("https://iglooidentityserver.azurewebsites.net/grants"))
        {
            AccessTokenUrl = new Uri("https://iglooidentityserver.azurewebsites.net/connect/token"),
            ShouldEncounterOnPageLoading = false,
        };

            var presenter = new OAuthLoginPresenter();
            presenter.Completed += Presenter_Completed;
            presenter.Login(oAuth);

最佳答案

我在一个旧项目中处理了这个问题,如下,希望这对你有帮助。

public async Task<string> GetAccessToken()
{
    if ((_authService.AuthAccessTokenExpireIn - DateTime.Now).TotalMinutes < 10) {
        var authResponse = await GetRefreshTokenAsync(_authService.AuthRefreshToken);
        
        _authService.AuthAccessToken = authResponse.AccessToken;
        _authService.AuthRefreshToken = authResponse.RefreshToken;
        _authService.AuthAccessTokenExpireIn = authResponse.ExpiresIn;
    }

    return _authService.AuthAccessToken;
}

public async Task<UserToken> GetRefreshTokenAsync(string currentRefreshToken)
{
    string data = string.Format("grant_type=refresh_token&client_id={0}&client_secret={1}&refresh_token={2}", GlobalSetting.Instance.ClientId, GlobalSetting.Instance.ClientSecret, refreshToken);
    var token = await PostAsync<UserToken>(_httpClient,
     GlobalSetting.Instance.TokenEndpoint, 
     data);
    return token;
}

public async Task<UserToken> PostAsync<UserToken>(HttpClient httpClient, string uri, object data)
{

    var content = new StringContent(JsonConvert.SerializeObject(data));
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
    HttpResponseMessage response = await httpClient.PostAsync(uri, content);

    await HandleResponse(response);
    string serialized = await response.Content.ReadAsStringAsync();

    UserToken result = await Task.Run(() => JsonConvert.DeserializeObject<UserToken>(serialized, _serializerSettings));

    return result;
}

关于xamarin.forms - 如何使用刷新 token 通过 Xamarin.Forms 客户端从身份服务器 4 获取新的访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56079375/

相关文章:

c# - 如何在 Xamarin.Forms 中使用 ShinyStartup?

xamarin.forms - 处理 Xamarin 表单 View /页面?

angular - 将 JWT token 存储到 HttpOnly cookie 中

c# - 签名验证失败。无法匹配 'kid'

identityserver4 - IClientStore 的自定义实现

reactjs - 如何使用并行响应刷新 Axios 中的身份验证 token ?

c# - 将文本设置为剪贴板 Xamarin

mvvm - Xamarin.forms 中用于控制值的 slider

angularjs - 如何在 Angular responseError 拦截器中处理多个响应

c# - IdentityServer4 刷新 token : How to determine expiration time?