Sub topic 7
JWT Bearer Flow for Server-to-Server Access
Prerequisites and scope
This chapter assumes you can create a connected app or external client app in Setup, that you know what a consumer key and a scope are, and that you can run curl and openssl. It covers the JWT bearer flow. Other chapters cover authorization code with PKCE and client credentials.
The JWT bearer flow lets a server get an access token without any user interaction. The server builds a small signed document (a JSON Web Token, or JWT), sends it to Salesforce, and receives an access token. Salesforce trusts the request because the signature matches a certificate you uploaded to the app in advance.
How the flow works
The caller proves its identity with a private key. Salesforce holds the matching public certificate. No password, no secret, and no browser redirect is involved.
Note that the response contains no refresh token. When the access token expires, the server signs a new JWT and asks again.
The JWT claims
A JWT has three parts: a header, a set of claims, and a signature. Salesforce requires four claims.
{
"iss": "<consumer key of the app>",
"sub": "[email protected]",
"aud": "https://login.salesforce.com",
"exp": 1767225600
}| Claim | Meaning | Common mistake |
|---|---|---|
| `iss` | The consumer key of the app | Using the consumer secret or the app name |
| `sub` | The Salesforce username the token will act as | Using an email address that is not the username |
| `aud` | The login URL: `https://login.salesforce.com`, `https://test.salesforce.com` for sandboxes, or your My Domain URL | Using a production audience for a sandbox |
| `exp` | Expiry as a Unix timestamp, in seconds | Setting it far in the future, or using milliseconds |
Keep exp a few minutes ahead of the current time. Salesforce rejects assertions that have already expired. Clock drift on your server can also cause failures, so keep it synchronized with NTP.
The header declares the signing algorithm, usually RS256. The signature is made with your private key over the encoded header and claims.
Setting up the app
Follow these steps once per integration.
- Generate a private key and a self-signed certificate.
- Create the app and enable OAuth settings.
- Upload the certificate and select the scopes the integration needs.
- Pre-authorize the user.
- Request a token.
Generate the key and certificate
openssl req -x509 -nodes -newkey rsa:2048 \
-keyout server.key -out server.crt -days 365 \
-subj "/CN=salesforce-integration"Keep server.key on your server or in a secrets manager. Upload only server.crt to Salesforce. The key never leaves your infrastructure.
Configure the app
In the app's OAuth settings:
- Enable OAuth and set a callback URL. The JWT flow does not use it, but Salesforce requires a value, so use a placeholder such as
https://localhost/callback. - Enable the option that uses digital signatures, and upload
server.crt. - Add the scopes. The
apiscope is typical. Withoutrefresh_tokenthere is no refresh token, which is fine here because this flow never issues one.
Pre-authorize the user
This is the step people skip most often. The JWT bearer flow cannot show a consent screen, so Salesforce must already know the user is allowed to use the app. Two settings achieve this:
- Set the app's permitted users policy to Admin approved users are pre-authorized.
- Assign the app to the user's profile or to a permission set that the user holds.
If the user is not pre-authorized, the request fails with invalid_grant and a message such as "user hasn't approved this consumer".
Requesting a token
Build and sign the assertion. This script produces a signed JWT with openssl.
b64url() { openssl base64 -A | tr '+/' '-_' | tr -d '='; }
HEADER=$(printf '{"alg":"RS256","typ":"JWT"}' | b64url)
EXP=$(( $(date +%s) + 180 ))
CLAIMS=$(printf '{"iss":"%s","sub":"%s","aud":"https://login.salesforce.com","exp":%s}' \
"$CONSUMER_KEY" "[email protected]" "$EXP" | b64url)
SIGNATURE=$(printf '%s.%s' "$HEADER" "$CLAIMS" \
| openssl dgst -sha256 -sign server.key -binary | b64url)
SIGNED_JWT="$HEADER.$CLAIMS.$SIGNATURE"Then exchange it for an access token.
curl -X POST https://login.salesforce.com/services/oauth2/token \
-d grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \
--data-urlencode assertion="$SIGNED_JWT"A successful response looks like this:
{
"access_token": "00D...!AQ...",
"scope": "api",
"instance_url": "https://MyDomain.my.salesforce.com",
"id": "https://login.salesforce.com/id/00D.../005...",
"token_type": "Bearer"
}Use --data-urlencode for the assertion. The signed JWT is safe in a URL, but the habit protects you if you later add other values.
Verify the token by calling the REST API versions resource:
curl https://MyDomain.my.salesforce.com/services/data/ \
-H "Authorization: Bearer $ACCESS_TOKEN"A list of API versions confirms the token works. Always send API calls to the instance_url returned in the response.
Using the Salesforce CLI
For CI pipelines, the Salesforce CLI performs the signing for you.
sf org login jwt \
--client-id "$CONSUMER_KEY" \
--jwt-key-file server.key \
--username [email protected] \
--instance-url https://login.salesforce.com \
--alias ci-orgIn a pipeline, store the private key as a protected secret and write it to a temporary file at run time. Delete the file when the job ends. Use --instance-url https://test.salesforce.com for sandboxes, or your My Domain URL when the org requires it.
Access control and the run-as user
The token carries the permissions of the user named in sub. The app's scopes limit what the token can do, and the user's profile and permission sets limit what that user can do. The token gets the narrower set of the two.
Use a dedicated integration user rather than a named employee. Give that user a permission set with only the object and field access the integration needs. Then an employee leaving the company does not break the integration, and an audit shows clearly which actions came from automation.
Common errors
| Error | Likely cause | Fix |
|---|---|---|
| `invalid_grant` with "user hasn't approved this consumer" | User is not pre-authorized | Set the permitted users policy to admin approved and assign a profile or permission set |
| `invalid_grant` with "audience is invalid" | `aud` does not match the login host | Use the login URL, test URL, or My Domain URL that you are posting to |
| `invalid_grant` with "invalid assertion" | Wrong key, wrong certificate, or bad encoding | Confirm the certificate in the app matches `server.key`. Check base64url encoding |
| `invalid_grant` with "expired authorization code" or expiry messages | `exp` in the past or clock drift | Set `exp` a few minutes ahead and sync the clock |
| `invalid_client_id` | `iss` is not a valid consumer key | Copy the consumer key again from the app |
| `invalid_app_access` | IP restrictions or a policy blocks the call | Check IP relaxation and the user's login IP ranges |
Base64url differs from ordinary base64. It replaces + with - and / with _, and it removes the = padding. The most frequent signing bug is leaving ordinary base64 in place.
Design considerations
- No refresh tokens. Request a new token whenever the old one expires. Cache the token and reuse it until shortly before expiry instead of signing a new JWT for each API call.
- Certificate expiry. Salesforce accepts the certificate until it expires. Track the expiry date and upload a replacement before then.
- One key per integration. Sharing a key across systems makes rotation and incident response harder.
- Narrow scopes. Grant only the scopes the integration uses.
- Session policy. The app's session timeout settings affect how long the token stays valid.
Exercise
Your JWT bearer request returns invalid_grant with the message "user hasn't approved this consumer". The consumer key, certificate, and audience are all correct. What is wrong, and what two changes fix it?
Show answer
The user named in sub is not pre-authorized for the app, and the flow cannot show a consent screen. Set the app's permitted users policy to "Admin approved users are pre-authorized", and assign the app to the user through a profile or a permission set that the user holds.
Exercise
A teammate wants the private key stored in the connected app so the integration is easier to set up. Why is this wrong, and where should each half of the key pair live?
Show answer
The private key is the credential and must stay under your control. Upload only the public certificate (server.crt) to the app. Keep the private key (server.key) in your server's secrets manager or in a protected CI secret.