Sub topic 14
Client credentials flow: server-to-server access without a user login
The client credentials flow lets a server get an access token using only the connected app's consumer key and consumer secret. No person logs in, and no signed assertion is needed. Salesforce runs every API call as one designated user, called the run-as user.
This chapter assumes you can already create a connected app, you know where your org's My Domain URL is, and you can read the token response fields covered earlier. You also need a Salesforce org where you have administrator access.
When this flow fits
Use it for a backend job, middleware, or a scheduled process where one fixed identity is acceptable. The flow trades flexibility for simplicity:
- There is no browser redirect, so there is no callback URL to handle.
- There is no per-user consent. Every request acts as the run-as user.
- There is no refresh token. When the access token expires, you request a new one.
- The only secret is the consumer secret, so protecting it matters more than in the other flows.
Configure the connected app
Start in Setup with the connected app, or External Client App, that your integration uses. The steps are:
- Under OAuth settings, enable OAuth and add the scopes the integration needs.
apiis typical. A callback URL is still required by the form, so enter a placeholder such ashttps://localhost/callback. This flow never uses it. - Select Enable Client Credentials Flow and accept the warning that the flow uses a single run-as user.
- Save, then open the app's Manage page and choose Edit Policies.
- Under Client Credentials Flow, set Run As to the integration user.
- Copy the consumer key and consumer secret from Manage Consumer Details.
The run-as user must exist before you can select it. Give that user a profile and permission sets that grant only the data and objects the integration needs. A dedicated user with the API Only access setting is a good choice, because nobody can then use it to log in through the UI.
The token request
The request goes to your org's My Domain URL, not to login.salesforce.com. The generic login host does not know which org's connected app you mean, so the request fails.
curl -X POST https://MyDomainName.my.salesforce.com/services/oauth2/token \
-d grant_type=client_credentials \
-d client_id=<CONSUMER_KEY> \
-d client_secret=<CONSUMER_SECRET>For a sandbox, the host looks like MyDomainName--sandboxname.sandbox.my.salesforce.com. A successful response is JSON with fields such as these:
| Field | Meaning |
|---|---|
| `access_token` | The bearer token to send on API calls |
| `instance_url` | The base URL for REST calls |
| `token_type` | `Bearer` |
| `scope` | The scopes actually granted |
| `issued_at` | Issue time in milliseconds since the epoch |
| `id` | Identity URL of the run-as user |
There is no refresh_token field, even if you request the refresh_token scope. The flow has no use for one, because the client can always authenticate again.
Call the API
As in every flow, the token goes in an Authorization header on a call to the instance_url from the response.
curl https://MyDomainName.my.salesforce.com/services/data/v60.0/limits \
-H "Authorization: Bearer <ACCESS_TOKEN>"Every record this call can see, and every change it can make, is bounded by the run-as user's permissions. Field-level security and sharing rules apply to that user exactly as they would in the UI.
A reusable client in Python
A real integration should cache the token and fetch a new one when Salesforce rejects it. The script below reads its settings from environment variables, so no secrets appear in source code.
import os
import requests
TOKEN_URL = os.environ["SF_MY_DOMAIN_URL"].rstrip("/") + "/services/oauth2/token"
CLIENT_ID = os.environ["SF_CONSUMER_KEY"]
CLIENT_SECRET = os.environ["SF_CONSUMER_SECRET"]
_token = None
def fetch_token():
resp = requests.post(
TOKEN_URL,
data={
"grant_type": "client_credentials",
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
},
timeout=30,
)
resp.raise_for_status()
return resp.json()
def get(path):
global _token
for attempt in range(2):
if _token is None:
_token = fetch_token()
resp = requests.get(
_token["instance_url"] + path,
headers={"Authorization": "Bearer " + _token["access_token"]},
timeout=30,
)
if resp.status_code == 401 and attempt == 0:
_token = None # expired or revoked: request a new one and retry once
continue
resp.raise_for_status()
return resp.json()
if __name__ == "__main__":
limits = get("/services/data/v60.0/limits")
print(limits["DailyApiRequests"])The retry happens only once. If a fresh token is also rejected, the cause is a configuration problem, and looping would only waste API calls.
Common errors
The error body is a JSON object with error and error_description. The description is usually the most useful part.
| Symptom | Likely cause |
|---|---|
| `unsupported_grant_type` | **Enable Client Credentials Flow** is not selected on the app |
| `invalid_grant` with a message about no client credentials user | No run-as user is set in the app's policies |
| `invalid_client_id` | The consumer key is wrong, or the app lives in a different org |
| `invalid_client` | The consumer secret is wrong or has been rotated |
| Failure against `login.salesforce.com` | The request must go to the My Domain URL |
| `invalid_grant` with an inactive user message | The run-as user is frozen, deactivated, or lacks API access |
| 403 or `INSUFFICIENT_ACCESS` on a call | The run-as user lacks permission for that object or field |
New or edited connected apps can take a few minutes to propagate. If a correct configuration still fails right after saving, wait briefly and retry.
Securing the run-as user and the secret
The consumer secret is a password for the run-as user's access. Anyone who holds it can obtain tokens without any further check. These practices reduce the risk:
- Store the secret in a secrets manager or in environment variables injected at deploy time. Never commit it.
- Keep the run-as user's permissions to the minimum the integration needs, using a dedicated permission set.
- Use a separate connected app and run-as user for each integration, so you can revoke one without affecting the others.
- Rotate the consumer secret on a schedule, and immediately if you suspect exposure.
- Restrict allowed IP ranges in the app's policies where your servers have stable addresses.
Exercise
Your integration gets invalid_grant from the token endpoint immediately after you enabled the client credentials flow on the connected app. The consumer key and secret are correct, and you are calling your My Domain URL. What is the most likely missing setting, and what should you do about the missing refresh token?
Show answer
The app's policies have no run-as user set, so Salesforce has no identity to issue the token for. Open the connected app's Manage page, choose Edit Policies, and select a Run As user under Client Credentials Flow. You do not need to handle a missing refresh token. This flow never returns one, so the integration requests a new access token with the same key and secret when the current one expires.