How to use RefreshRokens?

Hi,

Perhaps it's me not seeing the obvious, but referring to this page:

I really like this new feature as I am building an application that will be in use 24/7 and users may have changes - not committed to my XData server yet - at any time.

However, it is not clear to me how to practically implement this. Defining the ClientApp is clear but how do I get a new token? Via a TSphinxLogin method, or does the TSphinxLogin handle it automatically (keep refreshing until user logs off) or is there another mechanism to use?

A short explanation or small example would be appreciated!

When you get your access token, a refresh token will also be sent.
When your access token is expired, you can simply ask (via HTTP request) for another one, using the refresh token. No need to ask for the user to login again.

I saw that in the documentation indeed, but how to do that?

Can you give me a short example, perhaps some (pseudo-)code? Is there any reason it's not implemented in the TSphinxLogin component?

I assume that after login you use the following pseudo-code workflow to access your API:

var 
  AccessToken: string;
begin
  AccessToken := SphinxLogin1.AuthResult.AccessToken;
  // Call application API passing access token
  Client.Headers.SetValue('Authorization', 'Bearer ' + AccessToken;

If you call SphinxLogin1.IsLoggedIn and it returns false it means there is no access token, or it's expired.

If the access token is expired, you can perform a manual call to the Sphinx server passing the refresh token:

HttpClient.Url := 'http://sphinx-server-url/oauth/token';
HttpClient.Method := 'POST';
HttpClient.Headers.SetValue('Content-Type', 'application/x-www-form-urlencoded');
HttpClient.SetContent := 
  'grant_type=refresh_token' + 
  '&refresh_token=' + SphinxLogin.AuthResult.RefreshToken + 
  '&client_id=' + MyClientId';

Perform the request, the response will be a JSON with the renewed access token that you can continue using to perform the requests.

Not really, we just wanted to have it released asap for users who need it server side.
Indeed, we should implement this for TSphinxLogin (and TSphinxWebLogin) for an upcoming release.

1 Like