Sub topic 6
Authorization code flow with PKCE
This chapter assumes you can create a connected app or external client app with OAuth enabled, that you know what a consumer key and callback URL are, and that you can read a curl command. You will build a PKCE pair, send a user through authorization, redeem the code, and call the API.
When to use this flow
The authorization code flow is for integrations where a person signs in and approves access. Examples are web apps, mobile apps, and desktop tools. The user logs in at Salesforce, so your app never sees their password. Your app receives a short-lived authorization code and trades it for tokens.
PKCE (Proof Key for Code Exchange, pronounced "pixy") protects that trade. An attacker who steals the code in transit, for example from a redirect on a mobile device, cannot redeem it without a secret that only your app holds.
Use this flow when:
- A real user must be identified, and API calls should run as that user.
- The client cannot keep a secret, such as a single-page app or a mobile app.
- You want the user's own permissions and sharing rules to apply.
Use the JWT bearer or client credentials flows instead for unattended server-to-server jobs.
How PKCE works
PKCE adds two values to the standard flow:
- The code verifier is a random string your app generates and keeps. It must be 43 to 128 characters from the set
A-Z a-z 0-9 - . _ ~. - The code challenge is the SHA-256 hash of the verifier, encoded as base64url (base64 with
+and/replaced by-and_, and no=padding). Sendingcode_challenge_method=S256tells Salesforce which hash you used.
You send the challenge at the start. You send the verifier when you redeem the code. Salesforce hashes the verifier and compares it with the stored challenge. If they differ, the exchange fails.
Prerequisites in the app configuration
Before you run the flow, check these settings on the app:
- Enable OAuth is on, and the callback URL is registered. The
redirect_uriyou send must match a registered callback URL exactly, including scheme, host, path, and trailing slash. - The scopes you request are selected on the app. This flow normally needs
api, andrefresh_tokenif you want a refresh token. - Your app's PKCE setting. Connected apps have a "Require Proof Key for Code Exchange (PKCE) extension for Supported Authorization Flows" option. When it is on, requests without a challenge are rejected. Turn it on for every new app. External client apps expose an equivalent option in their OAuth settings.
- Secret handling. For connected apps, "Require Secret for Web Server Flow" is on by default, so the token request must also send
client_secret. Turn it off only for public clients that cannot protect a secret, and only together with required PKCE.
Step 1: Create the verifier and challenge
# Generate a PKCE code verifier and its S256 challenge
CODE_VERIFIER=$(openssl rand -base64 64 | tr -d '=+/\n' | cut -c1-64)
CODE_CHALLENGE=$(printf '%s' "$CODE_VERIFIER" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=')The first line produces 64 random characters drawn only from letters and digits, which is inside the allowed range. The second line hashes the verifier as raw bytes, base64-encodes the digest, converts it to the URL-safe alphabet, and strips padding.
Keep CODE_VERIFIER for step 3. In a real app, store it server-side in the user's session or, for a mobile app, in memory. Generate a new pair for every authorization attempt.
Step 2: Send the user to Salesforce
# Open this URL in a browser to start authorization
echo "https://MyDomain.my.salesforce.com/services/oauth2/authorize?response_type=code&client_id=$CONSUMER_KEY&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback&scope=api%20refresh_token&code_challenge=$CODE_CHALLENGE&code_challenge_method=S256"| Parameter | Purpose |
|---|---|
| `response_type=code` | Requests an authorization code. |
| `client_id` | The consumer key of the app. |
| `redirect_uri` | URL-encoded callback. Must match a registered value. |
| `scope` | Space-separated scopes, URL-encoded as `%20`. |
| `code_challenge` | The hashed verifier. |
| `code_challenge_method` | `S256`. |
Use your My Domain URL for the host. Use https://test.salesforce.com or your sandbox My Domain for sandboxes. You can also add a state parameter with a random value. Salesforce returns it unchanged, and your app should check it to block cross-site request forgery.
The user logs in and sees the approval screen. Salesforce then redirects to your callback URL:
https://app.example.com/callback?code=aPrx...%3D%3D&state=abc123The code is short-lived and single-use. Percent-decode it before you send it to the token endpoint, because codes often end in %3D.
Step 3: Redeem the code
# Exchange the returned code for tokens
curl -X POST https://MyDomain.my.salesforce.com/services/oauth2/token \
-d grant_type=authorization_code \
-d code="$AUTH_CODE" \
-d client_id="$CONSUMER_KEY" \
-d redirect_uri=https://app.example.com/callback \
-d code_verifier="$CODE_VERIFIER"This request omits client_secret, which is valid only if the app does not require a secret for the web server flow. If it does, add -d client_secret="$CONSUMER_SECRET". Server-side web apps should send both the secret and the verifier.
The response is JSON with these fields:
access_token: the bearer token for API calls.refresh_token: present if you requested therefresh_tokenscope and the app's policies allow it.instance_url: the host to use for API calls.id: a URL for the identity service.token_type,issued_at, andsignature.
Step 4: Verify the token
curl https://MyDomain.my.salesforce.com/services/data/ \
-H "Authorization: Bearer $ACCESS_TOKEN"A JSON list of API versions confirms the token works. To renew an expired access token without the user, post grant_type=refresh_token, the refresh_token, and the client_id to the same token endpoint.
Common errors and edge cases
invalid_grantwith "invalid authorization code": the code was used already, expired, or was not decoded. Restart the flow.invalid_grantwith "code verifier invalid" or a similar message: the verifier does not hash to the challenge. Typical causes are generating a new verifier between steps, hashing a string with a trailing newline, or using standard base64 instead of base64url.redirect_uri_mismatch: the callback differs from the registered value in any character.invalid_client_idorinvalid_client: wrong consumer key, an app not yet propagated, or a missing secret when one is required.OAUTH_APPROVAL_ERROR_GENERICor "user is not admin approved": the app's permitted users policy blocks this user. Fix it with the app policies and access control, covered in later chapters.- No refresh token returned: the
refresh_tokenscope was not requested or not enabled on the app, or the refresh token policy blocks it.
Exercise
A token request returns invalid_grant and the message says the code verifier is invalid. The authorization code was fresh and the redirect URI matched. Name two likely causes and how you would check each.
Show answer
First, the app generated a new verifier between the authorize step and the token step, so it no longer matches the stored challenge. Check that the same verifier value is saved per session and reused. Second, the challenge was computed incorrectly, for example using standard base64 with "+", "/" and "=" instead of base64url, or hashing text that included a trailing newline. Recompute the challenge from the saved verifier with the commands in step 1 and compare it with the code_challenge value sent in the authorize URL.