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?
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.