Sub topic 8
Hardening the web server flow with state and PKCE
This chapter assumes you have built a connected app with a callback URL and can run the basic web server flow from the previous chapter. You should be comfortable with query strings and short Python snippets.
Two attacks the plain flow allows
The redirect back to your app carries an authorization code in the URL. Two things can go wrong there:
- Forged callback (CSRF). An attacker sends your user a callback URL containing the attacker's own code. If your app accepts it, the user's session gets linked to the attacker's account. The
stateparameter prevents this. - Code interception. Malicious software or a leaked log captures the code from the redirect. If it can also reach the token endpoint, it can trade the code for tokens. PKCE (Proof Key for Code Exchange, pronounced "pixy") prevents this.
How state works
state is a random value your app creates before redirecting the user. Salesforce returns it unchanged on the callback. Your app compares the returned value with the one it stored in the user's session. If they differ, reject the request.
How PKCE works
PKCE binds the authorization request to the token request:
- Generate a random
code_verifier, 43 to 128 characters. - Compute
code_challenge, the Base64URL-encoded SHA-256 hash of the verifier, with no=padding. - Send the challenge and
code_challenge_method=S256in the authorization URL. - Send the original verifier when you exchange the code.
Salesforce hashes the verifier you send and compares it to the stored challenge. An attacker who steals only the code does not have the verifier.
Generating the values
import base64
import hashlib
import secrets
state = secrets.token_urlsafe(32)
code_verifier = secrets.token_urlsafe(64) # 86 characters
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
print("state:", state)
print("code_verifier:", code_verifier)
print("code_challenge:", code_challenge)Store state and code_verifier in the user's server-side session before the redirect. Put state and code_challenge into the authorization URL shown earlier. On the callback, check state first, then send code_verifier in the curl token request.
import hmac
def check_state(returned: str, stored: str) -> None:
if not hmac.compare_digest(returned, stored):
raise ValueError("state mismatch: reject the callback")Turning PKCE on in the connected app
In the connected app's OAuth settings, select Require Proof Key for Code Exchange (PKCE) extension for Supported Authorization Flows. Salesforce then rejects code exchanges that lack a valid verifier.
Common errors
invalid_grantwith a PKCE message usually means the verifier does not hash to the challenge. Check for padding=characters, the wrong hash, or a verifier regenerated between requests.- Losing the verifier between redirect and callback happens when the session is not persisted, for example across load-balanced servers.
Exercise
An attacker captures the authorization code from a redirect URL. Why can't they exchange it for an access token if the app used PKCE, and which parameter did they not have?
Show answer
The token endpoint requires the original codeverifier, and Salesforce checks that its SHA-256 hash matches the codechallenge sent earlier. The verifier never appeared in the redirect, so the attacker does not have it and the exchange fails.