Sub topic 8
Authenticating the Integration with OAuth
This chapter covers how the integration user signs in to Salesforce without a person typing a password. It assumes you know OAuth 2.0 basics (clients, tokens, scopes), can read a REST API call, and have already created the integration user and its permission set in earlier chapters.
Why OAuth fits an integration user
An integration user is a "run-as" identity. Every API call the integration makes executes with that user's permissions. The permission set you built decides what the calls can do. OAuth decides how the integration proves it is allowed to act as that user.
Avoid the older alternative, which is the SOAP login() call or a username-and-password OAuth flow. Both put the user's password, and often a security token, into the integration's configuration. Passwords are long-lived, easy to copy, and often reused. OAuth replaces them with a signed assertion or a short-lived access token that you can scope, revoke, and rotate.
Two parts are involved:
- The OAuth app definition in Salesforce. This is a connected app, or an external client app in newer orgs. It holds the client ID, the allowed scopes, and the policies for who may use it.
- The pre-authorized user. Salesforce is told in advance that this specific user, through a profile or permission set, may use the app. No consent screen appears at runtime.
Choosing a flow
Salesforce supports several OAuth flows. For an unattended server process, two are realistic.
| Flow | Credential held by the integration | Needs a user interaction | Typical use |
|---|---|---|---|
| JWT bearer | Private key (certificate pair) | No | Server-to-server jobs, CI pipelines, scheduled sync |
| Client credentials | Client ID and client secret | No | Server-to-server when you prefer a secret over a key pair |
| Web server (authorization code) | Client secret plus a refresh token | Yes, once | Apps acting for a person, not a dedicated service identity |
| Username-password | User password | No | Avoid. Legacy and discouraged |
This chapter uses the JWT bearer flow because the topic's example commands use it, and because the credential is a private key that never leaves your server. Only a signature crosses the network.
The client credentials flow is a good alternative. In it you name a single "run as" user in the app's policies, and the token is issued for that user. The pre-authorization and least-privilege rules below apply equally to it.
How the JWT bearer flow works
The integration builds a small signed JSON Web Token (JWT) and exchanges it for an access token. Salesforce checks the signature against the certificate you uploaded to the app.
The JWT contains four claims:
iss: the app's client ID (consumer key).sub: the integration user's username.aud: the login URL,https://login.salesforce.comfor production orhttps://test.salesforce.comfor a sandbox.exp: an expiry a few minutes in the future.
The response contains an access token and the instance URL. The JWT flow does not return a refresh token. When the access token expires, the integration signs a new JWT and asks again. That is simpler to operate than refresh-token storage, and there is no long-lived token to leak.
Setting up the app
The exact screens differ between connected apps and external client apps, but the decisions are the same.
- Create a certificate and key pair. Generate a private key and a self-signed certificate. Keep the private key (
server.key) in your secret store. Upload only the certificate to Salesforce. - Create the app. Enable OAuth settings and "Use digital signatures" so the app accepts the certificate.
- Select the narrowest scopes. Choose
apifor REST calls. Addrefresh_token, offline_accessonly if you use a flow that needs it, which JWT does not. Do not selectfull. - Set the policies. Set permitted users to "Admin approved users are pre-authorized." Salesforce then rejects anyone who has not been explicitly assigned.
- Pre-authorize the user. Assign the app to the integration user through a permission set (preferred) or the user's profile.
- Record the client ID. The integration needs it as the
issclaim.
Scopes are a ceiling, not a grant
An OAuth scope limits what a token may do. It never adds permissions the user lacks. A token with the api scope still cannot read an object the user has no read access to. The reverse also holds: if you choose a broad scope such as full, you widen the ceiling for no benefit, and a bug or stolen token has more room to cause harm. Pick api and let the permission set do the real restriction.
Pre-authorize with a permission set, not the profile
Assigning the app through a permission set keeps the profile minimal and makes access easy to remove. To add it, open the permission set and grant access to the app in its assigned connected apps (or external client apps) section. Then the "Admin approved users are pre-authorized" policy lets exactly the users holding that permission set in.
Logging in from the command line
The Salesforce CLI can test the flow end to end. This logs in as the integration user in a sandbox, then runs a query.
sf org login jwt \
--client-id "$SF_CLIENT_ID" \
--jwt-key-file server.key \
--username [email protected] \
--instance-url https://test.salesforce.com \
--alias integration-sandbox
sf data query \
--target-org integration-sandbox \
--query "SELECT Id, Name, Industry FROM Account LIMIT 5"Read the command closely:
--client-idtakes the app's consumer key from an environment variable, so it is not typed into shell history.--jwt-key-filepoints at the private key. Restrict its file permissions to the account that runs the integration.--instance-urlselects the sandbox login host. Usehttps://login.salesforce.com(or your My Domain URL) in production.--aliasnames the stored login so later commands can target it.
A successful query proves the signature, the pre-authorization, and the object read permission all work. The more important test is a denial: run the same command against an object the permission set does not include and confirm it fails. The chapter on verification covers this in detail.
Calling the token endpoint yourself
In a real integration you usually call the token endpoint from code rather than the CLI. This Python example builds the JWT and exchanges it. It needs the PyJWT, cryptography, and requests packages.
import os
import time
import jwt
import requests
LOGIN_URL = "https://test.salesforce.com" # use login.salesforce.com or your My Domain in production
def get_access_token() -> dict:
with open("server.key", "rb") as f:
private_key = f.read()
claims = {
"iss": os.environ["SF_CLIENT_ID"],
"sub": os.environ["SF_USERNAME"],
"aud": LOGIN_URL,
"exp": int(time.time()) + 180,
}
assertion = jwt.encode(claims, private_key, algorithm="RS256")
response = requests.post(
f"{LOGIN_URL}/services/oauth2/token",
data={
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
},
timeout=30,
)
response.raise_for_status()
return response.json()
if __name__ == "__main__":
token = get_access_token()
print("Instance URL:", token["instance_url"])Notes on the code:
- The expiry is three minutes out. Salesforce rejects assertions that expire too far ahead, so keep it short.
- The token request goes to the login host, but later API calls go to the
instance_urlin the response. - The script prints the instance URL and never the access token. Do not log tokens.
raise_for_status()turns a 400 response into an exception. Read the response body for the Salesforce error code before retrying.
Common failures
| Error | Likely cause | Fix |
|---|---|---|
| `invalid_grant: user hasn't approved this consumer` | User not pre-authorized for the app | Assign the app through a permission set or profile |
| `invalid_grant: audience is invalid` | `aud` does not match the login host | Use the sandbox or production host that matches the org |
| `invalid_grant: invalid assertion` | Certificate in the app does not match the private key, or the clock is wrong | Re-upload the certificate, and check server time sync |
| `invalid_client_id` | Wrong consumer key, or the app is in another org | Copy the key from the correct org's app |
| `API_DISABLED_FOR_ORG` or `INSUFFICIENT_ACCESS` after login | Login worked but the permission set lacks `ApiEnabled` or object access | Fix the permission set, not the OAuth setup |
The last row matters for diagnosis. A successful token means authentication works. Failures after that point are authorization problems and belong to the permission set and sharing layers.
Handling the credential safely
The private key is now the integration's identity. Anyone who holds it can sign in as the user, from anywhere that the network controls allow.
- Store the key in a secrets manager or the CI platform's secret store, not in the repository.
- Give each environment its own key pair and its own app, so a leaked sandbox key cannot reach production.
- Plan for rotation: the app can hold a certificate, so schedule a replacement before the old one expires and swap the key in your secret store.
- Treat access tokens as secrets too. They are short-lived, but they work until they expire.
Network restrictions, the topic of the next chapter, limit the damage if a key does leak. OAuth proves who is calling, and the network rules limit where the call may come from.
Exercise
An integration logs in with the JWT bearer flow and receives a valid access token, but a query on the Contact object returns an insufficient access error. The connected app uses the full scope. A teammate suggests the scope is too narrow. Is that the cause, and what should you check and change?
Show answer
The scope is not the cause. A scope is a ceiling on what a token can do and never grants object access. Because authentication succeeded, the OAuth setup works, so check the integration user's permission set for read access to Contact, and check field-level security and sharing for the records involved. Add only the Contact read access that the integration needs. Also replace the full scope with api, because full widens the ceiling without helping and is more than a least-privilege integration needs.
Exercise
Why does the JWT bearer flow need no refresh token, and what does the integration do when its access token expires?
Show answer
The integration holds a private key, which lets it prove its identity at any time. When the access token expires, it signs a new JWT with short expiry and sends it to the token endpoint to get a new access token. No long-lived refresh token has to be stored or protected.