Sub topic 8
Hardening the web server flow with state and PKCE
This chapter assumes you have read the web server flow chapter. You should know what a connected app is, what the callback URL does, and how an authorization code becomes an access token. You should be comfortable with HTTP redirects and form-encoded POST bodies. You should also be able to read short Python snippets.
The basic web server flow has two weak points. Both involve the redirect back to your app. The state parameter and PKCE (Proof Key for Code Exchange) each close one of them.
What the redirect exposes
In the web server flow, the browser carries data between your app and Salesforce. Two requests pass through the browser:
- Your app sends the user to the authorization URL.
- Salesforce redirects the user back to your callback URL with a
codequery parameter.
Anything that passes through the browser can be observed or forged by something other than your app. That leads to two attacks.
| Attack | What happens | Defense |
|---|---|---|
| Cross-site request forgery (CSRF) on the callback | An attacker gets the victim's browser to hit your callback URL with the attacker's own authorization code. The victim's session ends up linked to the attacker's account. | `state` |
| Authorization code interception | Malware, a malicious browser extension, a leaked log, or another app registered for the same redirect scheme captures the code. The attacker then redeems it. | PKCE |
These defenses are independent. state protects your app from accepting a response it did not ask for. PKCE protects the code from being redeemed by someone who did not start the flow. Use both.
The state parameter
state is an opaque string that your app creates and Salesforce returns unchanged. It lets your app check that a callback belongs to a login it started.
The procedure has four steps:
- Generate a random, unguessable value before redirecting the user.
- Store it somewhere tied to this browser session, such as a server-side session or a signed, HttpOnly cookie.
- Send it as
statein the authorization URL. - On the callback, compare the returned
statewith the stored value. Reject the request if they differ or if no stored value exists. Delete the stored value after one use.
The value must come from a cryptographically secure random source. A timestamp or a counter is guessable, so an attacker could forge it.
import secrets
state = secrets.token_urlsafe(32)
print(state)You can also use state to carry a small amount of your own data, such as the page the user was on. If you do, keep the random part separate and verify it. Do not put secrets in state, because it is visible in the URL.
PKCE
PKCE is defined in RFC 7636. It binds the authorization request to the token request using a one-time secret that never travels in the first request in a usable form.
PKCE uses two values:
- The code verifier is a random string, 43 to 128 characters long, using the characters
A-Z a-z 0-9 - . _ ~. Your app keeps it private. - The code challenge is derived from the verifier. With the
S256method, it is the Base64URL encoding (no padding) of the SHA-256 hash of the verifier.
The flow goes like this:
- Your app generates a verifier and computes the challenge.
- The authorization request includes
code_challengeandcode_challenge_method=S256. - Salesforce stores the challenge with the issued authorization code.
- The token request includes
code_verifier. - Salesforce hashes the verifier and compares the result with the stored challenge. It issues tokens only if they match.
An attacker who steals the code from the redirect does not know the verifier. The challenge is a hash, so it cannot be reversed to get the verifier. The stolen code is therefore useless.
Generating the values
This script produces a state, a verifier, and a challenge, then builds the authorization URL. It uses only the Python standard library.
import base64
import hashlib
import secrets
from urllib.parse import urlencode
CONSUMER_KEY = "<CONSUMER_KEY>"
REDIRECT_URI = "https://app.example.com/oauth/callback"
LOGIN_URL = "https://login.salesforce.com" # use https://test.salesforce.com for sandboxes
state = secrets.token_urlsafe(32)
# 32 random bytes encode to 43 URL-safe characters, the minimum allowed length.
code_verifier = secrets.token_urlsafe(32)
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
params = {
"response_type": "code",
"client_id": CONSUMER_KEY,
"redirect_uri": REDIRECT_URI,
"scope": "api refresh_token",
"state": state,
"code_challenge": code_challenge,
"code_challenge_method": "S256",
}
print("Store in session:", state, code_verifier)
print(f"{LOGIN_URL}/services/oauth2/authorize?{urlencode(params)}")urlencode handles the escaping for you. That includes the encoded redirect_uri and the space in scope.
Run the script, store the printed state and code_verifier in the user's session, and open the URL. After login and approval, Salesforce redirects to your callback URL with code and state.
Verifying and redeeming
On the callback, check state first. Only then exchange the code. This sketch uses Flask and shows the order of operations. It assumes the authorization step stored state and code_verifier in session.
import hmac
import os
import requests
from flask import Flask, abort, request, session
app = Flask(__name__)
app.secret_key = os.environ["FLASK_SECRET_KEY"]
CONSUMER_KEY = os.environ["SF_CONSUMER_KEY"]
CONSUMER_SECRET = os.environ["SF_CONSUMER_SECRET"]
REDIRECT_URI = "https://app.example.com/oauth/callback"
LOGIN_URL = "https://login.salesforce.com"
@app.route("/oauth/callback")
def callback():
expected_state = session.pop("oauth_state", None)
code_verifier = session.pop("code_verifier", None)
returned_state = request.args.get("state", "")
if not expected_state or not code_verifier:
abort(400, "No login in progress")
if not hmac.compare_digest(expected_state, returned_state):
abort(400, "State mismatch")
if "error" in request.args:
abort(400, request.args.get("error_description", "Authorization failed"))
resp = requests.post(
f"{LOGIN_URL}/services/oauth2/token",
data={
"grant_type": "authorization_code",
"code": request.args["code"],
"client_id": CONSUMER_KEY,
"client_secret": CONSUMER_SECRET,
"redirect_uri": REDIRECT_URI,
"code_verifier": code_verifier,
},
timeout=10,
)
resp.raise_for_status()
token = resp.json()
return {"instance_url": token["instance_url"]}Three details matter here:
session.popreads and deletes in one step, so eachstateand verifier works once.hmac.compare_digestdoes a constant-time comparison. A plain==works functionally, but the constant-time form is a good habit for security values.- The error check comes after the state check. A forged error response should not be trusted either.
Configuring the connected app
Salesforce needs to know how to treat PKCE for your connected app. In the connected app's OAuth settings, look at these options:
- Require Proof Key for Code Exchange (PKCE) extension for Supported Authorization Flows: when enabled, the authorization request must include a challenge, and the token request must include the matching verifier. Turn this on for any app that can send PKCE.
- Require Secret for Web Server Flow: when enabled, the token request must include
client_secret. A server-side app that can keep a secret should keep this on.
If PKCE is optional on the connected app and you send a challenge, Salesforce still enforces it. If you send a challenge in the authorization request and then omit code_verifier in the token request, the token request fails with invalid_grant.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `invalid_grant` with a message about the code verifier | The verifier sent does not hash to the stored challenge. Often the app generated a new verifier on the callback, or the session lost the original. | Persist the verifier from the authorization step. Do not regenerate it. |
| `invalid_grant` with "expired authorization code" | The code was not redeemed quickly enough, or was already used. | Redeem right away. Start the flow again. Codes are single use. |
| Challenge accepted but token request fails | The challenge was computed with padding (`=`) or with standard Base64 (`+` and `/`). | Use URL-safe Base64 and strip the `=` padding. |
| `state` mismatch on callback | Session cookie not sent on the redirect, multiple tabs overwriting one stored value, or a forged request. | Check cookie `SameSite` settings. Key stored state per login attempt if you allow concurrent logins. |
| `redirect_uri_mismatch` | The `redirect_uri` differs from the connected app's callback URL, or between the two requests. | Use the exact same string in both requests, and register it in the connected app. |
Edge cases
- Use S256, not plain. RFC 7636 also defines
plain, where the challenge equals the verifier. It gives no protection if someone can see the authorization request. Sendcode_challenge_method=S256. - Concurrent logins. If a user opens two login tabs, a single session slot for
statelets the second login overwrite the first. Store a map of state to verifier, or encode a login ID in the cookie. - State lifetime. Give stored values a short expiry, such as ten minutes, so abandoned logins do not accumulate.
- Verifier entropy. Use
secretsor an equivalent.random.random()is not suitable. - Refresh tokens. PKCE applies only to the authorization code exchange. The refresh token request does not carry a verifier.
Exercise
Your callback receives code and state, and the state matches. The token request then fails with invalid_grant. Your authorization URL included code_challenge_method=S256. Name two likely causes related to PKCE and how you would check each.
Show answer
First, the verifier sent in the token request may not be the one that produced the challenge. Check that the app reads the verifier from the stored session and does not generate a new one on the callback. Second, the challenge may have been encoded wrongly, for example with = padding or standard Base64 characters. Recompute it with URL-safe Base64 with padding stripped, and compare it with the value in the authorization URL. A third possibility is that the code was already used or had expired, so check that you redeem it once and promptly.
Exercise
Why is a timestamp a poor choice for state, and what does the callback do if the stored value is missing?
Show answer
A timestamp is predictable, so an attacker can guess it and craft a forged callback that passes the check. state should come from a cryptographically secure random source. If the stored value is missing, there is no login in progress for this session, so the callback must reject the request instead of continuing.