Sub topic 4
How the client credentials flow and run-as user work
This chapter assumes you know what an OAuth 2.0 access token is and can read short Python and curl examples. It also assumes you have an External Client App with OAuth enabled, from the previous chapter. Here you will learn what happens when your external system asks Salesforce for a token. You will also learn who the Agent API calls run as, and why that matters.
Why this flow fits the Agent API
Most OAuth flows involve a person. The web server flow redirects a user to a login page, and the user approves access. A server-to-server integration has no person present. A nightly job, a backend service, or a chat gateway cannot click "Allow".
The OAuth 2.0 client credentials flow handles this case. The calling system proves its own identity with a client ID and a client secret. Salesforce then issues an access token without any user login.
That raises a question. Every Salesforce API call executes as some user, and that user's permissions decide what the call can see and do. Because no one logs in during this flow, Salesforce needs another way to pick the user. The answer is the run-as user, which you configure on the app.
The three parties and the token exchange
| Party | Role in the flow |
|---|---|
| Your external system | Holds the client ID and secret, and sends the token request. |
| External Client App | Defines the client ID and secret, the allowed scopes, and the run-as user. |
| Run-as user | The Salesforce user whose identity and permissions the token carries. |
The exchange has four steps.
- Your system sends a POST request to
/services/oauth2/tokenon your My Domain. - Salesforce checks the client ID and secret against the External Client App.
- Salesforce confirms the app has the client credentials flow enabled and a run-as user assigned.
- Salesforce returns an access token bound to that user and to the scopes the app allows.
Configuring the app for the flow
Two settings make this flow work. If either is missing, the token request fails.
- Enable Client Credentials Flow. In the External Client App's OAuth settings, turn on the client credentials flow. Without this, the token endpoint rejects the
client_credentialsgrant type. - Run As user. In the app's OAuth policies, choose the user that tokens will represent. Salesforce does not let you leave this blank for this flow.
The scopes you selected earlier still apply. For the Agent API the app typically needs the api, chatbot_api, and sfap_api scopes. A token only carries scopes the app allows, so a missing scope shows up as a rejected Agent API call later, not as a token error.
A newly saved app can take a few minutes before the token endpoint accepts its credentials. If a request fails right after setup, wait briefly and retry before changing anything.
The token request in detail
The request is a form-encoded POST. The three fields are grant_type, client_id, and client_secret. Send the request to your My Domain URL, for example https://mycompany.my.salesforce.com. Do not use login.salesforce.com or test.salesforce.com. The client credentials flow is only supported on a My Domain endpoint, because the domain identifies which org's app you mean.
curl -X POST "$SF_MY_DOMAIN/services/oauth2/token" \
-d "grant_type=client_credentials" \
-d "client_id=$SF_CLIENT_ID" \
-d "client_secret=$SF_CLIENT_SECRET"A successful response is JSON. The exact fields can vary, but you can expect these:
{
"access_token": "00D...!AQ...",
"signature": "...",
"scope": "api chatbot_api sfap_api",
"instance_url": "https://mycompany.my.salesforce.com",
"id": "https://login.salesforce.com/id/00D.../005...",
"token_type": "Bearer",
"issued_at": "1764589602414"
}Several details matter here.
- No refresh token. This flow does not return one. When the token stops working, you request a new one with the same credentials.
- Expiry is not guaranteed in the body. Do not assume an
expires_infield is present. The lifetime comes from your org's session settings, so plan to handle a rejection instead of predicting one. - The
idURL names the run-as user. The last path segment is that user's ID. You can use it to confirm which identity the token carries. scopeshows what you actually got. Compare it against what you expected.
A token helper that checks what it receives
The following Python function requests a token and verifies that the scopes needed by the Agent API are present. It fails early with a clear message, which is easier to debug than a later 401 or 403 from the Agent API.
import os
import requests
MY_DOMAIN = os.environ["SF_MY_DOMAIN"] # for example https://mycompany.my.salesforce.com
REQUIRED_SCOPES = {"api", "chatbot_api", "sfap_api"}
def fetch_token() -> dict:
response = requests.post(
f"{MY_DOMAIN}/services/oauth2/token",
data={
"grant_type": "client_credentials",
"client_id": os.environ["SF_CLIENT_ID"],
"client_secret": os.environ["SF_CLIENT_SECRET"],
},
timeout=30,
)
if response.status_code != 200:
# Salesforce returns {"error": "...", "error_description": "..."}
detail = response.json() if response.content else {}
raise RuntimeError(
f"Token request failed ({response.status_code}): "
f"{detail.get('error')} - {detail.get('error_description')}"
)
payload = response.json()
granted = set(payload.get("scope", "").split())
missing = REQUIRED_SCOPES - granted
if missing:
raise RuntimeError(f"Token is missing scopes: {sorted(missing)}")
run_as_user_id = payload["id"].rsplit("/", 1)[-1]
print(f"Token issued for user {run_as_user_id}")
return payload
if __name__ == "__main__":
token = fetch_token()
print("Scopes:", token["scope"])The function prints the user ID, never the token. Keep it that way, because access tokens in logs are a common leak.
What the run-as user controls
Every call made with the token executes as the run-as user. This has three consequences.
- Agent access. The run-as user must be allowed to use the agent. If the user lacks the access your org requires, session creation fails even though the token is valid.
- Data access. When the agent runs actions that read or write records, the user's profile, permission sets, and sharing settings can limit the results. Two integrations with different run-as users can get different answers from the same agent.
- Audit trail. Records changed through the agent show that user as the actor. If many systems share one run-as user, you cannot tell them apart in the audit trail.
Treat the run-as user as a dedicated integration identity with narrow permissions. Do not use an administrator's account. If that account is deactivated, locked, or has its permissions changed, every integration using it breaks or gains unintended reach.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `unsupported_grant_type` | The client credentials flow is not enabled on the app. | Enable the flow in the app's OAuth settings. |
| `invalid_grant` with "no client credentials user enabled" | No run-as user is assigned. | Set the Run As user in the app's policies. |
| `invalid_client_id` or `invalid_client` | Wrong ID or secret, or the app was saved moments ago. | Re-copy the credentials and retry after a few minutes. |
| Token request fails against `login.salesforce.com` | Wrong host. | Use your My Domain URL. |
| Token works, but the Agent API returns 401 or 403 | Missing scope, or the run-as user cannot access the agent. | Compare `scope` in the response, then check the user's agent access. |
| Token worked yesterday, fails today | Run-as user deactivated, or the secret was rotated. | Check the user's status and the current secret. |
Decision notes
- One app per integration. Separate apps give you separate secrets, separate run-as users, and separate revocation. The cost is more setup. Sharing one app is simpler but makes rotation and auditing harder.
- Cache the token, but tolerate failure. Reusing a token avoids a token request on every call. Because expiry is not reported, cache it and request a new one when the API rejects it. The error-handling chapter covers that retry pattern.
- Secrets stay server-side. Client credentials identify your system, not an end user. Never put them in browser code or a mobile app.
Exercise
Your token request returns HTTP 400 with invalid_grant and the description "no client credentials user enabled". The client ID and secret are correct. What is wrong, and where do you fix it?
Show answer
The External Client App has no run-as user assigned. The client credentials flow has no login step to identify a user, so Salesforce needs a Run As user in the app's OAuth policies. Assign a dedicated integration user there, wait a few minutes if the app was just saved, and request the token again.
Exercise
A token request succeeds and the response has scope set to api. Later, the Agent API rejects your call. How would you find the cause, and what would you change?
Show answer
The scope value shows the token lacks chatbot_api and sfap_api, which the Agent API needs. Add those scopes to the External Client App's OAuth settings, then request a new token. An old token keeps its original scopes.