Salesforce: How to get the access token expires_at
How to fetch the expiration date of Salesforce access tokens
Salesforce breaks with a common OAuth convention: Their token endpoint does not return the expires_at
parameter, which indicates when the access token expires.
In this post we will show you how to retrieve the expiration date of Salesforce access tokens.
Problem: No expires_at in token response
A typical response from Salesforce’s access token endpoint looks like this:
The problem: This response does not tell us how long the access token is valid.
Without knowing the expiration date we don’t know when we have to go and refresh the access token with the refresh token.
How to fetch expires_at
To get the expiration date of the Salesforce OAuth access token we need to make and additional API request to a token introspection endpoint.
This endpoint tells us, amongst other things, when the access token is set to expire.
Raw HTTP request:
Or as a curl command:
The response for this request looks something like this:
There are two timestamps in here with cryptic names:
- exp: The expiration date of the access token in unix timestamp format. This is the
expires_at
value. - iat: The timestamp when the token was issued. Should match the
issued_at
parameter of the token response.
Refreshing the access token
You should refresh the Salesforce access token before it expires by using the refresh token from the token response.
We recommend refreshing the token a good bit before it expires: There are no penalties for this, but it minimizes the chance that your API requests fail due to an expired token.
Note that refreshes can also fail. We wrote a separate article on how to fix Salesforce refresh token errors.
Skip the hassle: Use Nango for Salesforce OAuth
Implementing Salesforce OAuth well is not trivial and can be time consuming.
Nango is an open-source solution for API authorization.
It has pre-built and battle tested implementations of the Salesforce OAuth flow and hundreds of other APIs.
It also handles:
- Automatic access token refreshes
- Keeping refresh tokens alive
- Secure token storage
- Detection of broken tokens
You can learn more about it on the Nango docs.