Sub topic 9
Refreshing access tokens
This chapter assumes you have completed the web server flow from the previous chapters. You should have a connected app with a callback URL, and you should be able to read a token response. You should also be comfortable with curl and form-encoded POST bodies.
Why access tokens expire
An access token is a short-lived credential. Salesforce ties its lifetime to the session settings of the org and the connected app, so you cannot assume a fixed number of minutes. Your integration will eventually get a rejected call, and it has to recover without asking the user to log in again.
A refresh token is a long-lived credential that lets your server request a new access token. The user does not see a login page. Salesforce issues a refresh token only when the user approved the right scope during the web server flow.
| Token | Lifetime | Used for | Sent to |
|---|---|---|---|
| Access token | Short, set by session policy | Calling the REST API | The `instance_url` |
| Refresh token | Long, set by the connected app policy | Getting new access tokens | The token endpoint |
Getting a refresh token in the first place
Salesforce returns a refresh token only if two conditions hold:
- The authorization request included the
refresh_tokenscope. The scope may also be writtenoffline_access. In the authorization URL from the web server flow, this is thescope=api%20refresh_tokenpart. - The connected app allows it. The app must have that scope selected in its OAuth settings, and its refresh token policy must not be "Expire refresh token immediately".
If either condition fails, the token response has no refresh_token field. Your code must treat that field as optional.
The refresh request
The refresh request goes to the same token endpoint you used for the authorization code exchange. Only the grant type and its parameters change.
curl -X POST https://login.salesforce.com/services/oauth2/token \
-d grant_type=refresh_token \
-d refresh_token=<REFRESH_TOKEN> \
-d client_id=<CONSUMER_KEY> \
-d client_secret=<CONSUMER_SECRET>Use your My Domain URL instead of login.salesforce.com if that is where the user authenticated. For a sandbox, use test.salesforce.com or the sandbox My Domain URL.
A successful response is JSON with these fields:
access_token: the new token to use in theAuthorizationheader.instance_url: the base URL for API calls. It normally matches the earlier value, but read it each time.token_type:Bearer.issued_at,signature,id, andscope: the same kind of metadata you saw after the first exchange.
The response usually does not contain a new refresh_token. Keep using the one you already have. Do not overwrite your stored refresh token with null when the field is missing.
When to refresh
There are two common strategies, and they have different failure modes.
| Strategy | How it works | Trade-off |
|---|---|---|
| Reactive | Call the API. If it returns `401` with `INVALID_SESSION_ID`, refresh and retry once. | Simple and always correct, but costs one failed call. |
| Proactive | Store an expiry time and refresh shortly before it. | Saves the failed call, but the expiry is a guess, because an admin can end the session early. |
Most production code uses the reactive approach, with proactive refresh only as an optimization. Salesforce does not always return an expiry time in the token response, and session settings can change after you receive the token. A reactive handler is the one that cannot be wrong.
A working refresh handler in Python
This script wraps an API call with one refresh and one retry. It reads secrets from environment variables, not from the source file.
import os
import requests
LOGIN_URL = os.environ.get("SF_LOGIN_URL", "https://login.salesforce.com")
CONSUMER_KEY = os.environ["SF_CONSUMER_KEY"]
CONSUMER_SECRET = os.environ["SF_CONSUMER_SECRET"]
def refresh_access_token(refresh_token):
resp = requests.post(
f"{LOGIN_URL}/services/oauth2/token",
data={
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": CONSUMER_KEY,
"client_secret": CONSUMER_SECRET,
},
timeout=30,
)
resp.raise_for_status()
return resp.json()
def call_api(session, path):
"""session is a dict with access_token, instance_url, refresh_token."""
url = session["instance_url"] + path
headers = {"Authorization": f"Bearer {session['access_token']}"}
resp = requests.get(url, headers=headers, timeout=30)
if resp.status_code == 401:
token = refresh_access_token(session["refresh_token"])
session["access_token"] = token["access_token"]
session["instance_url"] = token.get("instance_url", session["instance_url"])
headers = {"Authorization": f"Bearer {session['access_token']}"}
resp = requests.get(session["instance_url"] + path, headers=headers, timeout=30)
resp.raise_for_status()
return resp.json()
if __name__ == "__main__":
session = {
"access_token": os.environ["SF_ACCESS_TOKEN"],
"instance_url": os.environ["SF_INSTANCE_URL"],
"refresh_token": os.environ["SF_REFRESH_TOKEN"],
}
print(call_api(session, "/services/data/v60.0/limits"))The retry happens once. If the second call also fails with 401, the problem is not an expired token, and looping would only hide it.
Refresh token policies
The connected app controls how long a refresh token stays valid. You set this in the app's policies. The common options are:
- Refresh token is valid until revoked. This is the default and suits long-running integrations.
- Immediately expire refresh token. Salesforce issues no usable refresh token, so every session ends with the access token.
- Expire refresh token if not used for a set period.
- Expire refresh token after a fixed period.
A refresh token can also stop working for reasons outside the policy. An administrator can revoke it. The user can revoke it from their connected apps settings. The user can be deactivated or have their permissions removed. A later chapter covers revocation in detail.
Edge cases and errors
invalid_grant on refresh. The refresh token is no longer valid. Common causes are revocation, an expiry policy, a deactivated user, or a token copied from a different org or app. Retrying does not help. Your application must send the user through the web server flow again to get a new refresh token.
invalid_client_id or invalid_client. The consumer key or secret does not match the connected app that issued the refresh token. A refresh token only works with the app that created it.
Wrong login host. A refresh token from a sandbox fails at login.salesforce.com. Use the host that matches the org.
IP restrictions. If the connected app has IP relaxation settings, refresh requests from an unlisted address can fail. The app's IP policy applies to refresh requests as well.
Concurrent refreshes. If several workers notice the same 401 and all refresh at once, you send redundant requests. This is usually harmless because the refresh token is reusable. It is still worth guarding the refresh with a lock, so one worker refreshes and the others wait and reuse the result.
Storage. A refresh token is as sensitive as a password. Store it encrypted, scoped per user, and never in logs, URLs, or browser-visible storage.
Check your understanding
Exercise
Your web server flow app gets an access token, but the token response has no refresh_token field. Name two causes, and say what you would check first.
Show answer
Either the authorization request did not include the refreshtoken (or offlineaccess) scope, or the connected app does not have that scope enabled, or its refresh token policy is "Expire refresh token immediately". Check the scope parameter in the authorization URL first, because it is the quickest to confirm, then the connected app's selected OAuth scopes and refresh token policy.
Exercise
A refresh request returns {"error":"invalid_grant"}. Should your code retry it with the same refresh token? What should it do?
Show answer
No. invalid_grant means the refresh token is no longer valid, for example because it was revoked, expired by policy, or belongs to a deactivated user. Retrying gives the same result. The application should discard the stored token and send the user through the web server flow again.