Sub topic 12
JWT bearer flow: server-to-server access as a named user
This chapter assumes you have a connected app with a consumer key, you can generate a key pair with OpenSSL (covered in the previous chapters), and you can read short Python snippets. You should also know what an access token is and how to send it in an Authorization header.
What the flow does
The JWT bearer flow lets a server get an access token without any browser, redirect, or password prompt. The server builds a small signed document, called a JSON Web Token (JWT), and posts it to the Salesforce token endpoint. Salesforce checks the signature against a certificate you uploaded to the connected app. If the signature is valid and the named user is allowed to use the app, Salesforce returns an access token for that user.
The access token carries that user's permissions. Every API call the integration makes is audited as that user and is limited by that user's profile and permission sets.
The flow returns no refresh token. When the access token expires, the server signs a new JWT and asks again. That is cheap, because no user interaction is involved.
Roles in the exchange
| Role | Who plays it | What it holds |
|---|---|---|
| Client | Your integration server | Private key (`server.key`) |
| Authorization server | Salesforce login endpoint | Certificate (`server.crt`) uploaded to the connected app |
| Resource owner | The named Salesforce user | Permissions the token inherits |
| Resource server | The Salesforce REST API | Data, reached with the access token |
The private key never leaves your server. Salesforce only ever sees the certificate, which contains the public key.
Prerequisites in the org
Three things must be true before the request can succeed.
- The connected app has Use digital signatures enabled, with your
server.crtuploaded. - The connected app's OAuth scopes include at least
api. Addrefresh_tokenonly if you need it for another flow, because this flow does not return one. - The named user is pre-authorized. Set Permitted Users to Admin approved users are pre-authorized, then assign the user's profile or a permission set to the connected app.
Without pre-authorization, Salesforce has no way to ask the user for consent, so it rejects the request. This is the most common cause of a failed JWT setup.
If you still need a key pair, this command creates one:
openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 \
-keyout server.key -out server.crt -subj "/CN=sf-jwt-integration"The JWT claims
The JWT has a header and a set of claims, and the signature covers both. Salesforce requires four claims.
| Claim | Meaning | Value |
|---|---|---|
| `iss` | Issuer | The connected app's consumer key |
| `sub` | Subject | The Salesforce username of the named user |
| `aud` | Audience | The login URL: `https://login.salesforce.com`, `https://test.salesforce.com` for sandboxes, or your My Domain URL |
| `exp` | Expiration | Seconds since the Unix epoch. Keep it within a few minutes of now |
The signing algorithm is RS256, which means RSA with SHA-256. Keep exp short, such as two minutes. The assertion is only used once, immediately, so a long lifetime gains nothing and widens the window for replay if it leaks.
The aud value must match the login host you post to. Use the sandbox host for sandbox orgs, and the same host for the token request.
Building and sending the assertion
This script signs the JWT and exchanges it for an access token. It uses PyJWT with the cryptography package installed (pip install pyjwt cryptography requests).
import time
import jwt # PyJWT, with the cryptography package installed
import requests
CONSUMER_KEY = "<CONSUMER_KEY>"
USERNAME = "[email protected]"
LOGIN_URL = "https://login.salesforce.com" # use https://test.salesforce.com for sandboxes
with open("server.key", "rb") as f:
private_key = f.read()
claims = {
"iss": CONSUMER_KEY,
"sub": USERNAME,
"aud": LOGIN_URL,
"exp": int(time.time()) + 120,
}
assertion = jwt.encode(claims, private_key, algorithm="RS256")
resp = requests.post(
f"{LOGIN_URL}/services/oauth2/token",
data={
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
},
)
resp.raise_for_status()
token = resp.json()
print(token["instance_url"])The request has only two form fields. Note what is missing: there is no client_id and no client_secret. The consumer key travels inside the signed assertion as iss, and the signature proves you hold the private key, so no shared secret is sent.
The exchange step by step
The following diagram shows the sequence of messages between the three parties.
Using the response
A successful response is JSON. The fields you will use are access_token, instance_url, token_type (always Bearer), and scope. Send the token to the instance_url, not to the login host:
curl https://MyDomainName.my.salesforce.com/services/data/v60.0/limits \
-H "Authorization: Bearer <ACCESS_TOKEN>"Salesforce does not tell you the token lifetime in this response. Its lifetime follows the session settings of the org and the connected app. A robust client does not predict expiry. It makes the call, and if it receives a 401 with INVALID_SESSION_ID, it signs a fresh JWT and retries once.
Common errors
The token endpoint returns JSON with error and error_description. These are the ones you will meet most often with this flow.
| Error description | Likely cause | Fix |
|---|---|---|
| `invalid_grant` / `user hasn't approved this consumer` | User is not pre-authorized | Set Permitted Users to admin approved, and assign the profile or permission set to the app |
| `invalid_grant` / `invalid assertion` | Signature does not match the uploaded certificate, or `aud` is wrong | Upload the certificate that matches `server.key`, and check the `aud` host |
| `invalid_grant` / `expired authorization code` or an expiry message | `exp` is in the past, or the server clock is wrong | Sync the clock with NTP and compute `exp` at signing time |
| `invalid_client_id` | `iss` is not a valid consumer key | Copy the key from the connected app again |
| `invalid_grant` / `no such user` | `sub` is not a username in that org | Use the username, not the email address, and the right org (sandbox usernames carry a suffix) |
Connected app changes can take a few minutes to take effect after you save them. If a correct configuration fails right after setup, wait and retry before changing anything.
Edge cases and trade-offs
- Named user, not a service identity. The token acts as a real user. If that person leaves and the account is deactivated, the integration stops. Use a dedicated integration user instead of a person's account.
- Rotation. Certificates expire. The example certificate is valid for 365 days. Upload the new certificate before the old one lapses, and plan a deployment of the new key. Track the expiry date.
- One user per assertion. To act for many users, the server signs a separate JWT for each
sub, and each user must be pre-authorized. - Least privilege. Give the integration user a permission set with only the object and field access the integration needs. The scope limits what the token can do at the API level, but the user's permissions still apply on top.
- Key storage. Keep
server.keyin a secrets manager or an encrypted store, not in source control.
Exercises
Exercise
Your JWT request returns invalid_grant with the description "user hasn't approved this consumer". The signature and claims are correct. What do you change in the org?
Show answer
Pre-authorize the user. On the connected app, set Permitted Users to "Admin approved users are pre-authorized", then assign the user's profile or a permission set to the app. The flow has no consent screen, so Salesforce cannot ask the user to approve.
Exercise
Why does the JWT bearer token request contain no client secret, and what proves the caller's identity instead?
Show answer
The consumer key is sent as the iss claim, and the JWT is signed with a private key that only the integration server holds. Salesforce verifies the signature with the certificate uploaded to the connected app. A valid signature proves possession of the private key, so no shared secret is needed.
Exercise
You deploy the same script against a sandbox and get invalid_grant. The connected app and user exist there. Name two values in the script you should check.
Show answer
Check LOGIN_URL, which must be https://test.salesforce.com (or the sandbox My Domain URL) for both the aud claim and the token request. Check USERNAME, because sandbox usernames carry a suffix such as .sandboxname.