How to refresh access token provided by TokenCredential / ClientSecretCredential by Azure Identity Java SDK?

4.3k views Asked by At

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

There are 2 answers

3
juunas On

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.

0
weidongxu On

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.