Sub topic 2
Authenticating with OAuth 2.0
Every Salesforce API call needs proof of who is calling. Salesforce uses OAuth 2.0 for this. A client obtains an access token and sends it in the Authorization header of each request. This chapter covers the working model, the flows you will use most, and the errors that come up most often.
This chapter assumes you know basic HTTP and JSON, understand Salesforce objects and records, and can read a short curl command. You do not need prior OAuth knowledge.
The working model
OAuth 2.0 separates two things: proving identity and calling the API. The client does not send a username and password with every request. It exchanges credentials once for an access token, then uses that token until it expires.
Four pieces take part in every flow:
- The connected app (or external client app) is the configuration record in Salesforce that registers your client. It holds the consumer key (the client ID), the consumer secret (the client secret), the allowed OAuth scopes, and the callback URLs.
- The client is your integration, such as a server job, a web app, or a script.
- The authorization server is Salesforce itself. Its token endpoint is
https://MyDomain.my.salesforce.com/services/oauth2/token. - The resource server is the API you want to call, such as the REST API on the same domain.
The access token is short-lived. Some flows also return a refresh token, which is a long-lived credential that lets the client get a new access token without asking the user again. The token response also includes an instance_url. Use that value as the base URL for API calls.
A scope limits what a token can do. Common scopes are api (call the data APIs), refresh_token (receive a refresh token), and full (everything the user can do). Request the narrowest scope that works.
Set up the connected app first
No flow works until Salesforce knows about your client. In Setup, create a connected app (newer orgs may steer you to an external client app, which plays the same role). You choose the OAuth scopes, add a callback URL if the flow needs one, and record the consumer key and secret.
Treat the consumer secret like a password. Keep it in an environment variable or a secrets manager. Never commit it to source control or put it in browser code.
Use your My Domain URL for every OAuth call. The examples in this tutorial use MyDomain.my.salesforce.com. Replace it with your own domain. Use https://login.salesforce.com only when you do not have a My Domain, and https://test.salesforce.com for sandboxes without one.
Choosing a flow
Salesforce supports several flows. The right one depends on who is acting and where the client runs.
| Flow | Who acts | Typical client | Notes |
|---|---|---|---|
| Client credentials | An integration user, no person present | Server-to-server integration | Needs a "run as" user set on the app. No refresh token. |
| Authorization code with PKCE | A person who logs in | Web apps, single-page apps, mobile apps | Interactive. PKCE protects public clients. |
| JWT bearer | A pre-approved user, no person present | Server jobs, CI pipelines | Client signs a JWT with a private key. |
| Device flow | A person on another device | CLI tools, TVs, devices without a browser | User enters a code on a second screen. |
| Username-password | A person, credentials sent directly | Legacy scripts only | Discouraged. Often blocked by default. |
For a new server-to-server integration, start with client credentials or JWT bearer. For anything where a person signs in, use authorization code with PKCE.
Client credentials flow
This flow suits a back-end service that acts as one fixed user. In the connected app, enable the client credentials flow and choose a run as user. Every token the app obtains acts as that user, so the user's permissions decide what the integration can read and write.
curl -X POST "https://MyDomain.my.salesforce.com/services/oauth2/token" \
-d "grant_type=client_credentials" \
-d "client_id=$CLIENT_ID" \
-d "client_secret=$CLIENT_SECRET"A successful response looks like this:
{
"access_token": "00D...!AQ...",
"signature": "abc123...",
"scope": "api",
"instance_url": "https://MyDomain.my.salesforce.com",
"id": "https://login.salesforce.com/id/00D.../005...",
"token_type": "Bearer",
"issued_at": "1764577999000"
}Read access_token and instance_url from the response. Then send the token on every API call:
curl "https://MyDomain.my.salesforce.com/services/data/v60.0/limits" \
-H "Authorization: Bearer $ACCESS_TOKEN"The flow returns no refresh token. When the access token expires, repeat the token request. That is cheap, so a service can simply request a new token when it gets a 401.
Create a dedicated integration user for the run-as role. Give that user a permission set with only the object and field access the integration needs. Do not use a named admin's account.
Authorization code flow with PKCE
Use this when a person signs in and your client acts on their behalf. The steps are:
- The client generates a random code verifier and derives a code challenge from it with SHA-256.
- The client sends the user's browser to the Salesforce authorize endpoint with the challenge.
- The user logs in and approves access.
- Salesforce redirects the browser to your callback URL with a one-time authorization code.
- The client posts the code and the original verifier to the token endpoint and receives tokens.
PKCE (Proof Key for Code Exchange) means a stolen authorization code is useless without the verifier. It is the right choice for single-page and mobile apps, which cannot keep a secret safely. Use it for server-side web apps too.
The authorize request is a URL, not an API call:
echo "https://MyDomain.my.salesforce.com/services/oauth2/authorize?response_type=code&client_id=$CLIENT_ID&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback&scope=api%20refresh_token&code_challenge=$CODE_CHALLENGE&code_challenge_method=S256"After the redirect, exchange the code:
curl -X POST "https://MyDomain.my.salesforce.com/services/oauth2/token" \
-d "grant_type=authorization_code" \
-d "code=$AUTH_CODE" \
-d "client_id=$CLIENT_ID" \
-d "redirect_uri=https://app.example.com/callback" \
-d "code_verifier=$CODE_VERIFIER"Include client_secret as well if your app is a confidential server-side client that requires one.
Using the refresh token
When the access token expires, trade the refresh token for a new one:
curl -X POST "https://MyDomain.my.salesforce.com/services/oauth2/token" \
-d "grant_type=refresh_token" \
-d "refresh_token=$REFRESH_TOKEN" \
-d "client_id=$CLIENT_ID"Store refresh tokens encrypted. Anyone who holds one can mint access tokens until an administrator revokes it or the connected app's refresh token policy expires it.
JWT bearer flow
This flow suits unattended jobs that must act as a specific user, such as a nightly sync or a CI pipeline. You upload a certificate to the connected app. The client signs a short JWT with the matching private key and posts it to the token endpoint. No browser is involved and no secret travels over the network.
The JWT claims are:
iss: the consumer key.sub: the username of the user to act as.aud: the login URL, such ashttps://login.salesforce.com.exp: expiry, a few minutes in the future.
The user must be pre-authorized for the app, either through a permission set or profile assigned to the app, or by approving it once. The token request is:
curl -X POST "https://MyDomain.my.salesforce.com/services/oauth2/token" \
-d "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer" \
-d "assertion=$SIGNED_JWT"Common errors
Most failed authentication attempts come from configuration, not code. The token endpoint returns a JSON body with error and error_description.
| Error | Likely cause | Fix |
|---|---|---|
| `invalid_client_id` | Wrong consumer key, or the app is not yet propagated | Check the key. Wait a few minutes after creating the app. |
| `invalid_client` | Wrong secret, or the flow is not enabled on the app | Check the secret and the app's OAuth settings. |
| `invalid_grant` | Expired or reused code, bad JWT, user not pre-authorized, or wrong audience | Get a fresh code. Check `aud`, `sub`, and app authorization. |
| `unsupported_grant_type` | The flow is disabled for the org or app | Enable the flow in the connected app. |
| `redirect_uri_mismatch` | Callback URL differs from the one registered | Match the registered URL exactly, including the path. |
| `INVALID_SESSION_ID` (API, HTTP 401) | Access token expired or revoked | Request a new token, then retry once. |
If a call returns 401 and a fresh token still fails, check that you are calling the instance_url returned with the token, not a different org's domain.
Practical rules
- Send tokens only over HTTPS, in the
Authorizationheader and never in a URL query string. - Cache the token and reuse it. Requesting a new token for every API call wastes time and counts against login limits.
- Handle a 401 by getting a new token and retrying the call once. If it fails again, stop and report the error.
- Use a separate connected app per integration so you can revoke one without affecting others.
- Revoke tokens that are no longer needed by posting to
/services/oauth2/revoke.
Exercise
A nightly job in a CI pipeline must load data into Salesforce as a specific integration user. No person is available to log in, and the team does not want to store a client secret on the build server. Which flow fits best, and what must be true of the user before the first token request succeeds?
Show answer
The JWT bearer flow fits. The job signs a JWT with a private key whose certificate is uploaded to the connected app, so no client secret is needed. The integration user must be pre-authorized for the connected app, through an assigned profile or permission set or a one-time approval. Otherwise the token request fails with invalid_grant.
Exercise
Your server-to-server integration, using the client credentials flow, starts receiving HTTP 401 with INVALIDSESSIONID after running for a while. It never receives a refresh token. What should the client do?
Show answer
The access token has expired. The client should repeat the client credentials token request to get a new access token, then retry the failed call once. A refresh token is not needed because the flow can simply obtain a new token with the client ID and secret.