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

时间:2019-05-10 14:10:37

标签: xamarin.forms identityserver4 refresh-token

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

我遵循了教程https://sinclairinat0r.com/2018/12/09/secure-data-access-with-identityserver4-and-xamarin-forms,并在IS4上创建了具有身份验证功能的xamarin表单移动应用。我将访问令牌的生命周期设置为几分钟。在访问令牌过期之后(例外),应用程序将不再能够访问授权的端点。我有一个refresh_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);

1 个答案:

答案 0 :(得分:0)

我已经在一个旧项目中按如下方式处理了此问题,希望对您有帮助。

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;
}