What Is the Authorization Code Grant?
The Authorization Code grant is a two-step dance: first the client redirects the resource owner's browser to the authorization server's /authorize endpoint, where the user logs in and consents; the server then redirects back to the client's redirect_uri with a short-lived, single-use authorization code. The client's back end then exchanges that code for tokens at the /token endpoint, using its own credentials. Because the access token never touches the browser during step one, and the code itself is useless without the client's credentials, this flow keeps the most sensitive material off the front channel.
Cricket analogy: It mirrors MS Dhoni's lightning stumping: the wicketkeeper first collects the ball cleanly (the redirect with the code) before the actual dismissal (the token) is confirmed by the third umpire, never handing out the decision on the first touch alone.
Why PKCE? Proof Key for Code Exchange
PKCE (RFC 7636, pronounced 'pixy') was designed for public clients, apps like SPAs and native mobile apps that cannot hold a client secret because their code is fully exposed to the end user. Without PKCE, a malicious app on the same device could intercept the authorization code, for example via a hijacked custom URI scheme, and redeem it for tokens itself. PKCE closes this hole by having the legitimate client prove it is the same party that started the flow, using a secret it generates and never transmits until the very last step.
Cricket analogy: Imagine a team's game plan sheet for a match against Australia at the MCG leaking to a rival before play; PKCE is the equivalent of requiring the coach who wrote the plan to also produce the matching notebook it was torn from before anyone can act on it.
The PKCE Handshake in Detail
Before redirecting to /authorize, the client generates a high-entropy random string called the code_verifier (43-128 characters), then derives a code_challenge by SHA-256 hashing it and base64url-encoding the result, sending only the challenge and the method 'S256' in the authorization request. When the client later calls /token to redeem the code, it sends the original code_verifier in plaintext. The authorization server independently hashes the verifier and checks it matches the challenge it stored earlier; if they don't match, the token exchange is rejected outright, even if the attacker somehow obtained a valid authorization code.
Cricket analogy: It's like the DRS process: the fielding team submits a specific claim (the challenge) before the review starts, and only the ball-tracking data revealed afterward (the verifier) can confirm or overturn it, with no way to fake the match after the fact.
// 1. Generate a PKCE code_verifier and code_challenge (browser, SPA)
function base64url(buffer) {
return btoa(String.fromCharCode(...new Uint8Array(buffer)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
const codeVerifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
const challengeBuffer = await crypto.subtle.digest(
'SHA-256', new TextEncoder().encode(codeVerifier)
);
const codeChallenge = base64url(challengeBuffer);
sessionStorage.setItem('pkce_verifier', codeVerifier);
const authUrl = new URL('https://auth.example.com/authorize');
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('client_id', 'spa-client-123');
authUrl.searchParams.set('redirect_uri', 'https://app.example.com/callback');
authUrl.searchParams.set('scope', 'openid profile orders:read');
authUrl.searchParams.set('state', crypto.randomUUID());
authUrl.searchParams.set('code_challenge', codeChallenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
window.location.assign(authUrl.toString());
// 2. On /callback, exchange the code plus the stored verifier
const res = await fetch('https://auth.example.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
code: new URLSearchParams(location.search).get('code'),
redirect_uri: 'https://app.example.com/callback',
client_id: 'spa-client-123',
code_verifier: sessionStorage.getItem('pkce_verifier'),
}),
});
const tokens = await res.json();OAuth 2.1, the community effort to consolidate best practice, mandates PKCE for every Authorization Code flow, not just public clients. Even confidential clients with a client secret benefit from PKCE's protection against code interception, so most modern identity providers (Auth0, Okta, Azure AD) enable it by default for all client types.
Security Considerations Beyond PKCE
PKCE protects the code-for-token exchange, but two other controls matter just as much. The state parameter, an opaque random value the client generates and stores before redirecting, must be echoed back unchanged by the authorization server and verified on return; this prevents cross-site request forgery attacks where an attacker tricks a victim into completing a login flow initiated by the attacker. Separately, the authorization server must enforce exact, pre-registered redirect_uri matching (not just prefix matching), because a loosely validated redirect_uri is one of the most common real-world OAuth misconfigurations, letting attackers redirect codes to a domain they control.
Cricket analogy: It's like a match referee at Eden Gardens cross-checking the toss call against a sealed card filled in before the coin was even flipped, so no team can later claim a different outcome happened at the toss.
Never skip the state check to save a line of code. Without state validation, an attacker can start their own authorization flow, capture the resulting code, and trick a victim's browser into completing the exchange, effectively logging the victim into the attacker's account (a login CSRF attack). Always generate state per request and compare it server-side or in the SPA session before calling /token.
- The Authorization Code grant exchanges a short-lived code for tokens in a back-channel call, keeping tokens out of the browser's front channel.
- PKCE adds a code_verifier/code_challenge pair so a stolen authorization code cannot be redeemed by anyone other than the client that started the flow.
- code_challenge = base64url(SHA-256(code_verifier)); the method is sent as S256 in the authorize request and the verifier is revealed only at token exchange.
- OAuth 2.1 requires PKCE for all clients, public and confidential, as a defense-in-depth measure, not just an SPA/mobile requirement.
- The state parameter must be random per request and strictly verified on callback to prevent login CSRF attacks.
- Authorization servers must enforce exact redirect_uri matching against a pre-registered list to prevent code redirection attacks.
- Authorization codes are single-use and short-lived (often under a minute); replay attempts should be rejected and can indicate an active attack.
Practice what you learned
1. What problem does PKCE primarily solve in the Authorization Code grant?
2. How is the code_challenge derived when using the S256 method?
3. Why does OAuth 2.1 recommend PKCE for confidential clients too, not just public ones?
4. What is the role of the state parameter, distinct from PKCE?
5. Why must authorization servers enforce exact redirect_uri matching?
Was this page helpful?
You May Also Like
The Refresh Token Grant
Refresh tokens let a client obtain new access tokens without repeating the full authorization flow, keeping short-lived access tokens practical for long-running sessions.
The Client Credentials Grant
The Client Credentials grant lets a service authenticate as itself, without any user in the loop, making it the standard choice for machine-to-machine and backend-to-backend API access.
Choosing the Right Grant
OAuth 2.0 offers several grant types built for different trust boundaries; picking the wrong one is one of the most common real-world sources of OAuth vulnerabilities.
Deprecated Implicit and Password Grants
The Implicit and Resource Owner Password Credentials grants were early OAuth 2.0 patterns now formally deprecated in OAuth 2.1 due to fundamental security weaknesses, and understanding why matters for spotting legacy risk.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics