Sub topic 11
Pre-authorizing users for the JWT bearer flow
Why this flow needs pre-authorization
In the web server flow, the user sees a consent screen and approves your app. The JWT bearer flow has no browser and no consent screen. The server sends a signed assertion and expects a token back. Salesforce still needs to know that the user named in the assertion has agreed to let this connected app act for them. An administrator gives that agreement ahead of time. This is called pre-authorization.
This chapter assumes you have already created the connected app, uploaded the certificate from the key pair chapter, and selected the api scope. It covers the access policies that decide whether the token request succeeds.
If pre-authorization is missing, the token endpoint returns the most common JWT bearer error:
{"error":"invalid_grant","error_description":"user hasn't approved this consumer"}What Salesforce checks
When the token endpoint receives the assertion, it checks several things in order:
- The
issclaim matches a consumer key of a connected app in the org. - The signature verifies against a certificate uploaded to that app.
- The
subuser exists, is active, and can log in to the org. - The user is allowed to use the app, either by an admin policy or by earlier self-authorization.
- The request passes the app's IP restrictions.
Pre-authorization is step 4. The other steps produce different errors, which the troubleshooting section below covers.
Configure the connected app policies
In Setup, open App Manager, find the connected app, and choose Manage from the row menu. Then choose Edit Policies. Two settings matter here.
Permitted Users
This setting is under OAuth Policies. It has two values.
- All users may self-authorize: any user can approve the app through an interactive flow. A JWT request works only for a user who has already done that. A user who has never approved the app gets
invalid_grant. - Admin approved users are pre-authorized: only users assigned through profiles or permission sets may use the app. No user approval is needed or possible.
For a server-to-server integration, choose Admin approved users are pre-authorized. It makes access explicit and auditable, and it does not depend on someone having clicked Allow in a browser in the past.
IP Relaxation
The IP Relaxation setting controls whether the integration user's login IP ranges apply to this app. Your integration server probably runs in a cloud network outside the profile's trusted ranges. Two ways to deal with that:
- Set IP Relaxation to Relax IP restrictions. This is simple but removes a layer of protection for this app.
- Keep Enforce IP restrictions and add the server's fixed outbound addresses to the integration profile's login IP ranges, or to the connected app's trusted IP ranges. This is safer but requires stable egress addresses.
Save the policies.
Assign profiles or permission sets
Once the policy is Admin approved users are pre-authorized, nothing is authorized until you assign it. On the connected app's Manage page, use the Profiles and Permission Sets related lists, then choose Manage Profiles or Manage Permission Sets and select the entries.
Prefer a permission set over a profile.
| Option | Effect | Trade-off |
|---|---|---|
| Profile | Every user on that profile can use the app | Easy to over-grant, because a profile such as System Administrator covers many people |
| Permission set | Only users assigned the set can use the app | Needs one extra assignment step, but access is narrow and easy to revoke |
A practical pattern is a dedicated permission set, for example Integration_JWT_Access, that grants access to this one connected app. Assign it only to the integration user. Removing the assignment immediately blocks new JWT logins for that user.
A new or changed connected app can take a few minutes to become usable. If the setup is correct but the first request fails, wait and retry before changing anything.
Verify the assignment from the API
You can check which permission sets are linked to connected apps with a query. This uses the Salesforce CLI, which must already be authorized to the org:
sf data query --target-org my-org \
--query "SELECT SetupEntityId, Parent.Name, Parent.Profile.Name FROM SetupEntityAccess WHERE SetupEntityType = 'ConnectedApplication'"Each row links a permission set (Parent.Name) to a connected app (SetupEntityId). When the permission set belongs to a profile, Parent.Profile.Name shows the profile name. This is useful in deployment checks, because an app that exists with no assignments is a common cause of failed production launches.
Test the request and read the error
The script below signs an assertion and exchanges it, then prints Salesforce's error body when the request fails. It needs PyJWT, cryptography, and requests.
import sys
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,
},
timeout=30,
)
body = resp.json()
if resp.status_code != 200:
print(f"HTTP {resp.status_code}: {body.get('error')} - {body.get('error_description')}")
sys.exit(1)
print("instance_url:", body["instance_url"])Salesforce returns the failure reason in error_description. Use that text to find the cause.
| `error_description` | Likely cause | Fix |
|---|---|---|
| `user hasn't approved this consumer` | The user is not pre-authorized | Set Permitted Users to admin approved and assign a permission set or profile that includes the user |
| `invalid client credentials` or `client identifier invalid` | Wrong `iss`, or the app is not yet propagated | Check the consumer key and wait a few minutes after creating the app |
| `no user for this connected app` or `user not found` style messages | `sub` does not match an active username | Check the exact username. Sandbox usernames usually end in `.<sandboxname>` |
| `audience is invalid` | `aud` does not match the login host | Use `https://login.salesforce.com` for production and `https://test.salesforce.com` for sandboxes, or the My Domain URL |
| `invalid assertion` | Signature fails or the assertion has expired | Confirm the uploaded certificate matches `server.key` and the system clock is accurate |
Do not rely on exact wording alone. Messages can differ slightly between releases, so match on the error code and read the description for the detail.
Practical rules
- Use one integration user per integration, with a dedicated permission set for the connected app.
- Keep the user's other permissions minimal. Pre-authorization says the app may log in as this user, but the token carries all of the user's object and field access.
- After changing policies, test with the script from a clean shell, not a cached token.
- Include the connected app policies and permission set assignment in source control or deployment scripts so that a sandbox refresh does not silently drop them.
Exercise
A JWT bearer request for a newly created integration user returns invalid_grant with "user hasn't approved this consumer". The certificate is uploaded, the consumer key is correct, and the username is correct. The connected app's Permitted Users setting is "Admin approved users are pre-authorized". What is the most likely missing step, and how would you fix it so only this one user is covered?
Show answer
No profile or permission set is assigned to the connected app, so the user is not authorized. Create a permission set for the integration, assign it to the connected app with Manage Permission Sets, and assign the set to only the integration user. Retry after a few minutes in case the change has not propagated.
Exercise
Why is a permission set usually a better choice than a profile for pre-authorizing a connected app used by the JWT bearer flow?
Show answer
A profile grants the app to every user who has that profile, which can be many people. A permission set applies only to the users it is assigned to and can be removed from a single user to revoke access without affecting others.