APIAuthenticationFeaturedSecurity

OAuth 2.0 Authorization Code Flow with PKCE: A Practical Implementation Guide

6 Mins read
OAuth 2.0 Authorization Code Flow with PKCE: A Practical Implementation Guide

Building a Secure OAuth Login with PKCE

OAuth 2.0 Authorization Code Flow with PKCE helps apps obtain access tokens without exposing a client secret in software that users can inspect, such as mobile apps and single-page applications. PKCE (pronounced “pixie”) binds the authorization request to the later token exchange using a one-time code verifier. If an attacker intercepts the authorization code, they cannot redeem it without that verifier.

This practical guide explains the flow, shows how to create a code verifier and code challenge, and covers implementation choices and common security mistakes. The examples use browser-friendly JavaScript, but the same protocol applies to native apps and backend web applications.

What OAuth 2.0 Authorization Code Flow with PKCE Does

OAuth 2.0 lets a client request limited access to a resource on a user’s behalf. In the authorization code flow, the client sends the user to an authorization server to sign in and approve access. The server then redirects the user back with a short-lived authorization code. The client exchanges that code for tokens.

PKCE adds a proof to this exchange. Before redirecting the user, the client generates a secret value called a code verifier and derives a code challenge from it. The authorization server records the challenge. When the client later presents the code verifier at the token endpoint, the server checks that it matches.

PKCE is particularly important for public clients, which cannot safely keep a client secret. That includes mobile apps and browser-based apps. It is also recommended for confidential clients, such as server-side web applications, because it adds protection against authorization-code interception.

How the PKCE Authorization Code Flow Works

  1. The client generates a cryptographically random code verifier.
  2. The client derives a code challenge from the verifier using SHA-256.
  3. The client redirects the user to the authorization endpoint with the challenge, its method, and a unique state value.
  4. The user signs in and authorizes the requested access.
  5. The authorization server redirects to the registered callback with an authorization code and the original state.
  6. The client verifies the returned state and sends the authorization code and original code verifier to the token endpoint.
  7. The server validates the verifier against the earlier challenge and, if valid, returns tokens.

Use the S256 challenge method. It sends a SHA-256 hash of the verifier rather than the verifier itself. The older plain method offers weaker protection and should be avoided when S256 is supported.

Implementing PKCE in a Browser-Based App

1. Generate a code verifier and challenge

A verifier must be a high-entropy, unpredictable string that meets the format requirements in the OAuth specification. Do not use Math.random(), timestamps, or user data. In a browser, use the Web Crypto API:

function base64UrlEncode(bytes) {
  return btoa(String.fromCharCode(...bytes))
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");
}

function randomVerifier() {
  const bytes = crypto.getRandomValues(new Uint8Array(32));
  return base64UrlEncode(bytes);
}

async function createChallenge(verifier) {
  const data = new TextEncoder().encode(verifier);
  const digest = await crypto.subtle.digest("SHA-256", data);
  return base64UrlEncode(new Uint8Array(digest));
}

Thirty-two random bytes produce a verifier of suitable length after Base64URL encoding. Keep the verifier available until the callback is processed. For a browser app, temporary session storage is generally more appropriate than persistent local storage; clear it after use. Consider the threat model of your app and the risks of script injection, since malicious JavaScript running in the same origin may access browser storage.

2. Redirect to the authorization endpoint

Build the authorization request using values issued or configured for your application. The exact endpoint and parameters depend on your identity provider. A typical request includes:

  • response_type=code
  • Your registered client_id and exact redirect_uri
  • The requested scope
  • A fresh, unpredictable state value
  • code_challenge and code_challenge_method=S256

Generate and save state separately from the PKCE verifier. State helps the client detect a forged or mismatched callback; PKCE binds the code exchange to the initiating client instance. They address related but distinct risks.

const verifier = randomVerifier();
const challenge = await createChallenge(verifier);
const state = randomVerifier();

sessionStorage.setItem("pkce_verifier", verifier);
sessionStorage.setItem("oauth_state", state);

const params = new URLSearchParams({
  response_type: "code",
  client_id: "YOUR_CLIENT_ID",
  redirect_uri: "https://app.example.com/callback",
  scope: "openid profile email",
  state,
  code_challenge: challenge,
  code_challenge_method: "S256"
});

location.assign(
  `https://identity.example.com/authorize?${params}`
);

The openid scope is used with OpenID Connect when the application also needs to authenticate the user. OAuth itself is an authorization framework; it does not define a standard user sign-in identity token.

3. Validate the callback and exchange the code

On the callback page, read the authorization code and state from the URL. Compare the returned state with the saved value before proceeding. Reject the callback if state is missing or does not match. Then retrieve the verifier and make a form-encoded POST request to the token endpoint.

const callback = new URL(location.href);
const code = callback.searchParams.get("code");
const returnedState = callback.searchParams.get("state");

const expectedState = sessionStorage.getItem("oauth_state");
const verifier = sessionStorage.getItem("pkce_verifier");

if (!code || !expectedState || returnedState !== expectedState || !verifier) {
  throw new Error("Invalid OAuth callback");
}

const tokenResponse = await fetch(
  "https://identity.example.com/token",
  {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      client_id: "YOUR_CLIENT_ID",
      redirect_uri: "https://app.example.com/callback",
      code,
      code_verifier: verifier
    })
  }
);

if (!tokenResponse.ok) {
  throw new Error("Token exchange failed");
}

const tokens = await tokenResponse.json();
sessionStorage.removeItem("oauth_state");
sessionStorage.removeItem("pkce_verifier");

Do not include a client secret in a browser app. Public clients cannot keep secrets confidential. The authorization server must support public clients and PKCE, allow the registered redirect URI, and apply its own token and code validation rules. For production, use a maintained OAuth or OpenID Connect library where possible; it can handle protocol details that are easy to get wrong.

Security Checks That Matter

  • Use HTTPS: Protect authorization redirects, callbacks, and token requests in production.
  • Match redirect URIs exactly: Register specific callback URLs rather than permissive patterns or user-controlled destinations.
  • Verify state: Reject mismatches and remove saved transaction data after the callback.
  • Use a fresh verifier per attempt: Never reuse a verifier across login transactions.
  • Request minimum scopes: Ask only for the access the application needs.
  • Handle errors safely: Authorization servers may return an error instead of a code. Do not treat such a callback as a successful login.
  • Protect tokens: Avoid logging access or refresh tokens, and follow the provider’s guidance for token storage and renewal.

PKCE protects the authorization code exchange; it does not make every part of an application secure. It cannot compensate for a compromised device, cross-site scripting, an unsafe redirect URI, or careless token handling.

Trade-Offs and Common Pitfalls

PKCE adds a small amount of client-side state and an extra verifier check, but that is usually a favorable trade-off for the protection it provides. The more significant implementation choice is where token handling belongs. A browser-based app can exchange codes directly as a public client, but tokens exposed to browser JavaScript may be at greater risk from script injection. A backend-for-frontend can keep tokens server-side, at the cost of operating a backend and managing sessions.

  • Using the verifier as the challenge: This is not the recommended S256 flow. Hash the verifier and send the challenge method.
  • Sending the verifier in the authorization URL: The verifier belongs in the token request, not the initial redirect.
  • Skipping state because PKCE is enabled: Keep state validation. It provides a separate callback-correlation check.
  • Using a client secret in a public app: Bundled secrets can be extracted and should not be treated as confidential.
  • Accepting loosely matched callbacks: Broad redirect matching can enable attacks that redirect codes or tokens to an unintended location.
  • Assuming every provider behaves identically: Check provider documentation for endpoint URLs, supported scopes, CORS requirements, and token response details.

Small implementation choices matter beyond OAuth. For example, accessible controls and clear interaction patterns are important when building sign-in interfaces; see FromDev’s guide to improving accessibility with javascript:void(0) for JavaScript links. When maintaining older systems around a new authentication integration, the article on memmove in legacy code and modernization tips offers useful context for careful modernization. For teams running JavaScript tooling locally, see how to set the Node.js version in VS Code.

Testing Before Release

Test both successful and failed authorization paths. In particular, confirm that the app rejects a callback with a mismatched state, a missing verifier, an invalid code, or an unexpected redirect. Also test expired and reused codes: authorization codes should be short-lived and usable only once, according to the provider’s implementation.

Use the identity provider’s test environment where available. Keep real credentials and tokens out of source control, screenshots, logs, and bug reports. For production monitoring, log useful event details without recording secrets.

Conclusion

OAuth 2.0 Authorization Code Flow with PKCE gives public clients a safer way to exchange authorization codes by requiring proof of the original code verifier. Generate a strong verifier, send only its S256 challenge in the authorization request, validate state on the callback, and submit the verifier only when exchanging the code. Combine those steps with exact redirect URI matching, HTTPS, minimal scopes, and careful token handling. PKCE is straightforward to adopt, but its protection depends on implementing the entire flow deliberately.

Leave a Reply

Your email address will not be published. Required fields are marked *