0

I am trying to obtain an access token using the Azure Identity Java SDK and later refresh it using the refresh token.

I use the following SDK:

  <dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.1.2</version>
  </dependency>

Java code snippet:

  context = new AuthenticationContext(authority, false, service);
  ClientCredential credential = new ClientCredential(clientId, clientSecret);
  Future<AuthenticationResult> future = context.acquireToken(resource, credential, null);
  token = future.get().getAccessToken();

In the code snippet, the token has an expiration of 1 hour as expected, see Link.

The ClientSecretCredential implements the TokenCredential interface, which describes that refreshing the access token must be individually implemented.

I couldn't find any example on the Microsoft documentation (or other resources) that describes how to refresh the token using the Java SDK.

What is the correct way of refreshing the access token?

2 Answers2

0

When using client credentials authentication, the correct way is to ask for a new token from the ClientSecretCredential object. What you could use is a wrapper around the ClientSecretCredential that caches the returned token for, say 50 minutes, and then once that time has passed, it asks for a new token from the ClientSecretCredential.

juunas
  • 54,244
  • 13
  • 113
  • 149
  • Asking for a new token works, of course. But I was wondering how I would correctly **refresh** the token, e.g., by using the refresh token from the `future` object - which, however, is null in the code snippet. – Andreas Hessenthaler Oct 21 '20 at 11:28
  • There is no refresh token when using client credentials flow. – juunas Oct 21 '20 at 11:35
  • Thanks for your answer. Can you point to any documentation and / or code examples which demonstrate your suggested cache mechanism that includes the refresh mechanism? – Andreas Hessenthaler Oct 21 '20 at 12:03
0

I think the refresh process is abstracted away by azure-identity.

You can get the expire date via AccessToken.getExpiresAt.

For ClientSecretCredential, it probably does not need a refresh. SDK only need to fetch a new token (using the same secret), if last one expires.

For other e.g. InteractiveBrowserCredential which requires an interactive flow to get a new token, it makes sense for a refresh. It is handled in azure-identity here (you can see when the last token is expired or within 5min of its expire date, it will get force refreshed), and further in MSAL here.

Not official answer, just reading the code.

weidongxu
  • 303
  • 1
  • 7