Handling Expired Access Tokens

Most services providers return (or should return) access tokens with a limited lifespan. In general, access tokens usually expire about 30 to 60 minutes after being issued, although this is not a standard that strictly enforced by providers.

In the same way, providers often provide a refresh token with the access token. The refresh token is a second token that can be used to replace an expired access token with a fresh one, without the need to perform the dance again.

Unfortunately, there is no enforced standard that the SDK can use to automatically detect a token expiration scenario and obtain a new one. Different APIs communicate that in different ways. That is why the AccessTokenExpiredException exception exists.

public void someOperation(@Connection SalesforceRestClient client) { (1)
    Response response = client.performSomeOperation(); (2)
    if (response.getStatusCode() == 401) { (3)
        throw new AccessTokenExpiredException(); (4)
1 The example above uses an imaginary REST client to perform an operation. It assumes that this rest client was created through a ConnectionProvider annotated with @AuthorizationCode.
2 It performs the operation and gets a Response object that contains information of the HTTP call.
3 The example assumes that a status code of 401 (unauthorize) means that the token has expired.
4 It throws the AccessTokenExpiredException.

When the SDK detects this exception, it automatically performs the refresh dance and retries the operation with a new access token.

Note that in real life, different APIs notify you of the access token expiration in different ways. Some give you clients that throw exceptions, while others give you custom messages. You need to research the remote API to determine the best way to account for this.

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub