Sub topic 2
Authenticating with an OAuth access token
Every call to the Salesforce REST API needs proof of who is calling. This chapter covers how that proof works, how to get it, how to send it, and what failures look like. Later chapters reuse it in every request.
This chapter assumes you know basic HTTP (methods, headers, status codes), can read JSON, and can run curl or a short Python script. It also assumes you have a Salesforce org, such as a Developer Edition org, where you can create a connected app or external client app.
What an access token is
Salesforce uses OAuth 2.0 for API authentication. You never send a username and password with each request. You first exchange credentials for an access token. A token is a short opaque string that represents an authenticated session for one user in one org. You then send that token with every API call.
The REST API accepts the token in the Authorization header, using the Bearer scheme:
Authorization: Bearer 00Dxx0000001gPL!AQ4AQ..."Bearer" means that whoever holds the string can act as the user. Treat tokens like passwords:
- Keep them out of source control and logs.
- Send them only over HTTPS.
- Do not put them in URLs, where they end up in server logs and browser history.
The two values you get back
A successful token request returns more than the token. The two values you need for every REST call are:
access_token: the credential for theAuthorizationheader.instance_url: the base URL of the org that you send REST calls to, such ashttps://MyDomain.my.salesforce.com.
The next chapter builds resource URLs from instance_url. Always read it from the token response instead of hard-coding it. Salesforce can move an org to a different instance, and a hard-coded host breaks when that happens.
A typical response looks like this:
{
"access_token": "00Dxx0000001gPL!AQ4AQ...",
"signature": "<signature>",
"scope": "api",
"instance_url": "https://MyDomain.my.salesforce.com",
"id": "https://login.salesforce.com/id/00Dxx0000001gPLEAY/005xx000001SwiUAAS",
"token_type": "Bearer",
"issued_at": "1764576723038"
}The exact set of fields depends on the flow you use. For example, flows that issue refresh tokens add a refresh_token field. token_type is always Bearer for this API.
Where tokens come from: OAuth flows
A flow is a recipe for exchanging credentials for a token. Which one you choose depends on who is calling.
| Flow | Typical use | Notes |
|---|---|---|
| Authorization code (web server flow) | A web app acting for a human user | The user logs in and approves access. Can return a refresh token. |
| JWT bearer flow | Server-to-server integrations that act as a specific user | You sign a JWT with a private key. No interactive login. |
| Client credentials flow | Server-to-server integrations with a fixed run-as user | You send the client ID and secret. The connected app names the run-as user. |
| Username-password flow | Old scripts | Discouraged and often disabled. Avoid it in new work. |
All of these flows require you to register your application in the org. This is done with a connected app or, in newer orgs, an external client app. Registering gives you a client ID (the consumer key) and a client secret (the consumer secret). It is also where you grant the api OAuth scope, which allows REST API calls.
The sequence below shows the pattern shared by every flow. Only the first step differs.
Worked example: client credentials flow
The client credentials flow is the shortest to demonstrate. Before running it, configure the app in your org:
- Enable the client credentials flow in the app's OAuth settings.
- Select a run-as user for the app.
- Grant the
apiscope.
Then request a token from your My Domain URL. This flow uses your My Domain host, not login.salesforce.com.
export SF_LOGIN_URL="https://MyDomain.my.salesforce.com"
export SF_CLIENT_ID="<consumer key>"
export SF_CLIENT_SECRET="<consumer secret>"
curl -X POST "$SF_LOGIN_URL/services/oauth2/token" \
-d "grant_type=client_credentials" \
-d "client_id=$SF_CLIENT_ID" \
-d "client_secret=$SF_CLIENT_SECRET"The token endpoint expects form-encoded data (application/x-www-form-urlencoded), which is what curl -d sends. It does not take JSON.
The same exchange in Python, followed by a first authenticated call. The call reads the org's limits resource, which any user with API access can read and which has no side effects:
import os
import requests
login_url = os.environ["SF_LOGIN_URL"]
client_id = os.environ["SF_CLIENT_ID"]
client_secret = os.environ["SF_CLIENT_SECRET"]
version = os.environ.get("SF_API_VERSION", "v60.0")
# Step 1: exchange credentials for a token.
token_response = requests.post(
f"{login_url}/services/oauth2/token",
data={
"grant_type": "client_credentials",
"client_id": client_id,
"client_secret": client_secret,
},
timeout=30,
)
if not token_response.ok:
raise RuntimeError(f"{token_response.status_code}: {token_response.text}")
token = token_response.json()
access_token = token["access_token"]
instance_url = token["instance_url"]
# Step 2: send the token as a Bearer header on a REST call.
headers = {"Authorization": f"Bearer {access_token}"}
limits = requests.get(
f"{instance_url}/services/data/{version}/limits",
headers=headers,
timeout=30,
)
if not limits.ok:
raise RuntimeError(f"{limits.status_code}: {limits.text}")
daily = limits.json()["DailyApiRequests"]
print("Daily API requests remaining:", daily["Remaining"], "of", daily["Max"])If this prints a number, your authentication works and you can move on to creating records.
A shortcut for learning: the Salesforce CLI
For experiments you can skip the app registration and borrow a token from the Salesforce CLI. After you log in with sf org login web, this command prints the org details, including the access token and instance URL:
sf org display --target-org my-dev-orgCopy those two values into SF_ACCESS_TOKEN and SF_INSTANCE_URL. The token belongs to your own user and expires with your session. This is fine for learning, and it is the way the other chapters' curl examples can be run quickly. It is not a good basis for a production integration.
Token lifetime and expiry
Access tokens are short-lived. Their lifetime follows the session timeout settings of the org and the connected app, often two hours of inactivity by default. Once a token expires, or an administrator revokes the session, Salesforce rejects it with HTTP 401:
[
{
"message": "Session expired or invalid",
"errorCode": "INVALID_SESSION_ID"
}
]The response uses the standard error shape, a JSON array of objects, which a later chapter covers in full. A robust client reacts to INVALID_SESSION_ID like this:
- Request a new token with the same flow, or with the refresh token if the flow issued one.
- Retry the failed request once.
- If it fails again, stop and report the error. Do not retry in a loop.
Common authentication errors
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 with `INVALID_SESSION_ID` on a REST call | Token expired, revoked, or sent to the wrong org | Get a new token. Check that you use the `instance_url` that came with the token. |
| 400 from the token endpoint with `invalid_client_id` or `invalid_client` | Wrong consumer key or secret, or the app is not set up for this flow | Re-check the credentials and the app's OAuth settings. |
| 400 with `invalid_grant` | Bad or expired credentials for the flow, or the run-as user or certificate is not set up correctly | Review the flow's prerequisites for the app. |
| 403 on a REST call | The token is valid, but the user lacks permission | Check the user's profile or permission sets, including API access. |
| Token works in one org and fails in another | Tokens are per org, and sandbox and production use different hosts | Request the token from the correct login URL. |
Note the difference between 401 and 403. A 401 means Salesforce does not accept who you are. A 403 means it knows who you are and refuses the action.
Key points
- The REST API authenticates each request with an OAuth 2.0 access token in
Authorization: Bearer <token>. - A token response gives you
access_tokenandinstance_url. You need both for every call. - Choose the flow by caller type. Web apps use authorization code, and unattended servers use JWT bearer or client credentials.
- A 401 with
INVALID_SESSION_IDmeans the token is expired or invalid. Get a new token and retry once.
Exercise
Your script calls the REST API and receives HTTP 401 with the error code INVALIDSESSIONID. Another script, using a valid token for a user without permission to read a certain object, receives HTTP 403. Explain what each status means, and what your first script should do next.
Show answer
A 401 with INVALIDSESSIONID means Salesforce does not accept the token, usually because it expired or was revoked. The first script should request a new token with its OAuth flow (or use its refresh token), retry the request once, and report the error if it fails again. A 403 means the token is valid and the user is identified, but that user is not allowed to do the operation. Getting a new token will not fix it. The fix is to change the user's permissions.
Exercise
A token request returns an accesstoken and an instanceurl. Why should an integration use the returned instance_url instead of a host name saved in its configuration, and where in the request does the access token go?
Show answer
The org can be served from a different host than the one you configured, and sandboxes and production use different hosts, so the returned instanceurl is the correct base for REST calls and keeps code portable between orgs. The access token goes in the Authorization header as "Authorization: Bearer <accesstoken>", not in the URL or body.