Guide
Implementing OAuth 2.0 Authorization Code Flow with PKCE for SPA and Mobile Apps
Step-by-step guide to adding PKCE to the OAuth 2.0 Authorization Code flow, enabling secure token exchange for clients that cannot store a secret.
Published by Tasadduq Burney
28 Feb 2026, 22:00 UTC
2 min86.2K views0

Desired outcome
Successfully obtain an access token using the OAuth 2.0 Authorization Code Flow with PKCE, without storing a client secret.
Prerequisites
- OAuth 2.0 Authorization Server that supports PKCE (S256 method).
- Registered client ID with at least one redirect URI.
- Ability to generate cryptographically random strings and compute SHA-256 (available in modern browsers via Web Crypto API).
Procedure
- Generate code_verifier and code_challenge. Create a random string 43‑128 characters (alphanumeric plus -._~). Compute SHA‑256, then Base64URL‑encode to get the challenge. Store the verifier temporarily (e.g., sessionStorage).
-
Start the authorization request. Redirect the user to the AS
/authorizeendpoint with parameters:response_type=code,client_id=YOUR_CLIENT_ID,redirect_uri=YOUR_REDIRECT_URI,scope=openid%20profile,state=RANDOM_STATE,code_challenge=GENERATED_CHALLENGE,code_challenge_method=S256. -
Handle the redirect. After user authentication, the AS returns to
redirect_uriwithcodeand the originalstate. Verify the state matches the one you sent to mitigate CSRF. -
Exchange the authorization code for tokens. POST to the AS
/tokenendpoint withContent-Type: application/x-www-form-urlencodedand body:grant_type=authorization_code code=AUTHORIZATION_CODE_RECEIVED client_id=YOUR_CLIENT_ID redirect_uri=YOUR_REDIRECT_URI code_verifier=ORIGINAL_CODE_VERIFIER
-
Process the response. On success, the AS returns JSON containing
access_token, optionalrefresh_token, andtoken_type. Store the token securely (e.g., in-memory) and use it for API calls.
Expected checks
- Network tab shows the initial GET to
/authorizeincludescode_challengeandcode_challenge_method=S256. - The POST to
/tokenincludes the exactcode_verifiergenerated earlier. - Providing an incorrect verifier results in a 400 error from the token endpoint.
- A valid verifier yields a JSON response with an
access_tokenfield.
Recovery options
- If the state mismatch occurs, abort the flow and restart from step 1 with a new verifier/challenge.
- If the token endpoint returns 400 due to verifier failure, clear the stored verifier and repeat the flow.
- Network errors: retry the POST after a short back‑off, ensuring the verifier is still available.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.