Sub topic 5
Reading the token response
This chapter assumes you can make a token request with curl or Python, as shown in the earlier chapters on endpoints and connected apps. You should also know what a JSON object is and how an HTTP Authorization header works. Here you learn what each field in a successful token response means, which fields appear in which flow, and what your code should do with them.
What the response looks like
Every Salesforce flow ends with a POST to /services/oauth2/token. A successful call returns HTTP 200 and a JSON body like this one from a web server flow that requested api and refresh_token:
{
"access_token": "00D5g000001AbCd!AQEAQ...",
"refresh_token": "5Aep861...",
"signature": "k3Jv0o1Yf0c5n0q3mXQxZc0fVwqj6B9o1m3b7s8m2tI=",
"scope": "refresh_token api",
"instance_url": "https://MyDomainName.my.salesforce.com",
"id": "https://login.salesforce.com/id/00D5g000001AbCdEAK/0055g00000XyZ12AAB",
"token_type": "Bearer",
"issued_at": "1764578465123"
}The values above are shortened examples. Real tokens are longer.
Field reference
| Field | Meaning | Present in |
|---|---|---|
| `access_token` | The credential you send on API calls. | All three flows |
| `refresh_token` | A long-lived credential for getting new access tokens. | Web server flow, only if `refresh_token` scope was granted |
| `signature` | A Base64 HMAC-SHA256 value you can use to check the response. | Most responses |
| `scope` | The scopes actually granted. | All three flows |
| `instance_url` | The base URL for API calls. | All three flows |
| `id` | The identity URL of the user the token acts for. | All three flows |
| `token_type` | Always `Bearer`. | All three flows |
| `issued_at` | Creation time in milliseconds since the Unix epoch, as a string. | All three flows |
| `id_token` | An OpenID Connect token that describes the user. | Only if `openid` scope was granted |
Some fields depend on your org or flow. For example, responses for Experience Cloud sites can include extra URLs. Code that reads only the fields it needs keeps working when Salesforce adds new ones.
access_token
Treat the access token as an opaque string. Do not split it, decode it, or guess its format. It often begins with the 15-character org ID followed by !, but that is an implementation detail and can change. Your only job is to send it in an Authorization: Bearer header.
The response has no expires_in field. The token's lifetime comes from the session timeout set on the org or the connected app, and the token can also end early through revocation or an admin action. Do not hard-code a lifetime. Instead, handle a 401 response from the API (usually INVALID_SESSION_ID) by getting a new token, either with the refresh token or by repeating the JWT or client credentials request.
refresh_token
Only the web server flow can return a refresh token, and only when the app requested refresh_token (or offline_access) and the connected app policy allows it. The JWT bearer and client credentials flows never return one. When their access token stops working, you send a new signed assertion or a new client credentials request.
If you expected a refresh token and none arrived, check the scope field in the response before debugging anything else.
scope
The scope value is a space-separated list of what was granted. It can be narrower than what you requested. This can happen because of the connected app's selected scopes or because of policies on the user. Always read it. A response that lacks refresh_token in scope will not contain a refresh token.
instance_url
Use instance_url as the host for every API call. Do not build the host from the login URL you called, because the user's org may live on a different instance. This matters most when you authenticate against login.salesforce.com and the org has a My Domain. Store the value next to the token, because the pair belongs together.
id
The id field is the identity URL. A GET request to it with the bearer token returns details about the user and the org, such as the user ID, org ID, username, and URLs for the REST and SOAP APIs. The last path segment is the user ID, and the segment before it is the org ID.
issued_at
issued_at is a string of milliseconds. Convert it before doing date math. It tells you when Salesforce created the token, which helps with logging and with deciding when to proactively replace a token.
signature
The signature lets you check that the response was not altered in transit. Salesforce computes it as the Base64 encoding of an HMAC-SHA256 hash. The hashed message is the id value followed directly by the issued_at value, and the key is the connected app's consumer secret. Checking it is useful only when you hold the consumer secret. Public clients that have no secret cannot do this.
Parsing and checking a response in Python
The script below builds a sample response in memory, so you can run it without an org. It then checks the signature, converts issued_at, and extracts the instance URL and user ID.
import base64
import hashlib
import hmac
import json
from datetime import datetime, timezone
CONSUMER_SECRET = "example-consumer-secret"
def compute_signature(identity_url, issued_at, secret):
message = (identity_url + issued_at).encode("utf-8")
digest = hmac.new(secret.encode("utf-8"), message, hashlib.sha256).digest()
return base64.b64encode(digest).decode("ascii")
def read_token_response(body, secret):
data = json.loads(body)
signature = data.get("signature")
if signature is not None:
expected = compute_signature(data["id"], data["issued_at"], secret)
if not hmac.compare_digest(signature, expected):
raise ValueError("Token response signature does not match")
issued = datetime.fromtimestamp(int(data["issued_at"]) / 1000, tz=timezone.utc)
granted = set(data.get("scope", "").split())
return {
"access_token": data["access_token"],
"refresh_token": data.get("refresh_token"),
"instance_url": data["instance_url"],
"user_id": data["id"].rstrip("/").split("/")[-1],
"org_id": data["id"].rstrip("/").split("/")[-2],
"issued_at": issued,
"scopes": granted,
}
identity = "https://login.salesforce.com/id/00D5g000001AbCdEAK/0055g00000XyZ12AAB"
issued_at = "1764578465123"
sample = json.dumps({
"access_token": "00D5g000001AbCd!example",
"signature": compute_signature(identity, issued_at, CONSUMER_SECRET),
"scope": "api",
"instance_url": "https://MyDomainName.my.salesforce.com",
"id": identity,
"token_type": "Bearer",
"issued_at": issued_at,
})
result = read_token_response(sample, CONSUMER_SECRET)
print(result["instance_url"])
print(result["user_id"], result["org_id"])
print(result["issued_at"].isoformat())
print(sorted(result["scopes"]))
print("can refresh:", "refresh_token" in result["scopes"] and result["refresh_token"] is not None)The script uses hmac.compare_digest for the comparison so the check does not leak timing information. It also reads refresh_token with .get(), because that field is missing in two of the three flows.
Where each value goes next
The diagram shows how a client should use the fields after a successful response.
Errors use a different shape
A failed token request returns an HTTP 400 (or sometimes 401 or 403) with a small JSON body:
{
"error": "invalid_grant",
"error_description": "authentication failure"
}Check the HTTP status before you read fields. If your code calls data["access_token"] on an error body, you get a KeyError that hides the real cause. Log error and error_description instead, and never log the request body, because it can contain secrets.
Common mistakes
- Using
login.salesforce.comas the API host instead ofinstance_url. - Waiting for an
expires_infield that Salesforce does not send. - Expecting a
refresh_tokenfrom the JWT bearer or client credentials flow. - Treating
issued_atas seconds. It is milliseconds. - Reading
scopeas the list you asked for. It is the list you received.
Exercise
A client credentials request succeeds, but your code fails with a KeyError on refresh_token. A teammate suggests adding refresh_token to the request's scope. What is the correct diagnosis and fix?
Show answer
The client credentials flow never returns a refresh token, so the field is correctly absent and adding the scope will not change that. Read refresh_token with .get() (or skip it for this flow), and when the access token stops working (a 401 from the API), repeat the client credentials request to get a new one.
Exercise
The token response has "issued_at": "1764578465123". Write the Python expression that converts it to a timezone-aware UTC datetime, and explain why dividing by 1000 is needed.
Show answer
datetime.fromtimestamp(int("1764578465123") / 1000, tz=timezone.utc). Salesforce returns issued_at in milliseconds since the Unix epoch, but fromtimestamp expects seconds, so the value must be divided by 1000.