Sub topic 12
JWT bearer flow: server-to-server access as a named user
This chapter assumes you have a connected app with a certificate uploaded, a key pair on the integration server, and a user pre-authorized through a policy, profile, or permission set. Those steps come from earlier chapters. Here you build the assertion and exchange it for a token.
How the flow works
The JWT bearer flow lets a server get an access token without any browser or user interaction. The server signs a short JSON Web Token (JWT) with its private key. Salesforce checks the signature against the certificate stored in the connected app, confirms the user is pre-authorized, and returns an access token. The token acts as the named user in the sub claim.
The JWT claims
Four claims are required.
| Claim | Value | Meaning |
|---|---|---|
| `iss` | Consumer key | Identifies the connected app |
| `sub` | Username | The user the token acts as |
| `aud` | Login URL | `https://login.salesforce.com`, or `https://test.salesforce.com` for sandboxes |
| `exp` | Unix time | Expiry, kept short (a few minutes at most) |
The header uses the RS256 algorithm, which means RSA with SHA-256. The aud value must match the login host you post to. A My Domain URL is also accepted as the audience.
Build and send the assertion
This script uses the PyJWT package with cryptography installed, plus requests. It reads server.key, which was created with the openssl command from the key pair chapter.
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 response contains access_token, instance_url, token_type, and scope. Use instance_url as the base for API calls, as covered earlier. The flow returns no refresh token. When the access token expires, sign a new assertion and request another token.
Common errors
invalid_grantwith "user hasn't approved this consumer": the user is not pre-authorized. Set the connected app's Permitted Users policy to "Admin approved users are pre-authorized" and assign the profile or permission set.invalid_grantwith "invalid assertion": check that the certificate in the connected app matchesserver.key, and thataudmatches the host you are posting to.invalid_client_id: theissvalue is not the consumer key of an existing connected app.- Expired assertion:
expis in the past, or the server clock is out of sync. Synchronize time with NTP.
Exercise
Your script returns invalid_grant with the message "user hasn't approved this consumer". The certificate and consumer key are correct. What is missing, and why does this flow need it?
Show answer
The user is not pre-authorized for the connected app. The JWT bearer flow has no login screen where the user could approve access, so an admin must set the policy to "Admin approved users are pre-authorized" and assign the user's profile or a permission set to the connected app.