Erik Parso
Erik Parso

Reputation: 294

How to use refresh token to get a new access token from identity server 4 with Xamarin.Forms client

How to use refresh_token to obtain a new access token from identity server in Xamarin.Forms client?

I followed tutorial https://sinclairinat0r.com/2018/12/09/secure-data-access-with-identityserver4-and-xamarin-forms and created xamarin forms mobile app with authentication on IS4. I set an access token lifetime to few minutes. After access token expires, as excepted, applciation is no more able to access authorized endpoints. I have an refresh_token but i dont't know how to use it to obtain a new access token from identity server.

Client specified in is4 configuration:

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

Authenticator i've used:

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

Upvotes: 1

Views: 1885

Answers (1)

Denny Puig
Denny Puig

Reputation: 642

I handled this problem in an old project as follows, hope this helps you.

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

Upvotes: 1

Related Questions