404human Projects Writing Build logs Learning Books Progress
Rust · Zola
zsh · 404human@dev:~ Tab complete · ↑↓ history · type help

OAuth PKCE explained (with real code & traps)

What PKCE is in OAuth 2.1, why S256 stops authorization-code interception, runnable Python verifier/challenge code, and real remote MCP pitfalls.

Published
Read time
5 min read
Kind
guide
Topics

PKCE (Proof Key for Code Exchange, RFC 7636, pronounced “pixy”) is the one extra step in OAuth 2.1 that makes a stolen authorization code useless to an attacker.

If you are building a single-page app, a mobile app, a desktop CLI, or a remote MCP server that lets clients like Claude sign in as a real user (as we did for colophonapp.404human.dev/mcp in Colophon CMS), PKCE is mandatory—and surprisingly easy to get subtly wrong if you only skim the spec.

What is PKCE in OAuth? (The 30-second intuition)

In a plain OAuth authorization code flow, the server redirects the user’s browser back to your app with ?code=abc123 in the URL. Any malicious app registered on the same custom URI scheme (on mobile/desktop), or anything that reads browser history or proxy logs, can steal abc123 and trade it at /oauth/token for an access token.

PKCE fixes this by creating a one-time lock and key on the client before login starts:

  1. Before redirecting to login, the client generates a random secret string called the code_verifier (kept strictly in local memory).
  2. The client hashes it (SHA-256, base64url-encoded without =) to create the code_challenge, and sends only the hash in the login redirect (code_challenge=...&code_challenge_method=S256).
  3. The authorization server stores that hash beside the issued authorization code.
  4. When exchanging code at /oauth/token, the client sends the original secret code_verifier.
  5. The server hashes the received code_verifier and checks that it matches the stored code_challenge.

Even if an attacker intercepts the authorization code from the redirect URL, they don’t have the original code_verifier, so /oauth/token rejects the exchange.

Client (SPA / CLI / MCP)                    Authorization Server (/oauth)
  │                                                      │
  ├─ 1. verifier = random(32+ bytes)                     │
  ├─ 2. challenge = base64url(sha256(verifier))          │
  │                                                      │
  ├── 3. GET /oauth/authorize                            │
  │      ?code_challenge=<hash>&code_challenge_method=S256
  │                                     User approves ───┤
  │◄── 4. 302 redirect ?code=<code>&state=<state> ───────┤ (stores code + challenge)
  │                                                      │
  ├── 5. POST /oauth/token                               │
  │      code=<code>&code_verifier=<verifier> ──────────►│
  │                                                      ├─ sha256(verifier) == stored challenge?
  │◄── 6. 200 { access_token, refresh_token } ───────────┤ (burns single-use code)

Runnable PKCE code (client + server verification in Python)

You don’t need a heavy OAuth library to understand or verify PKCE. Here is the exact RFC 7636 S256 generation and constant-time server verification using Python’s standard library:

import base64
import hashlib
import hmac
import secrets


def base64url_nopad(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


def create_pkce_pair() -> tuple[str, str]:
    """Client side: generate a 43-char verifier (256 bits of entropy) and its S256 challenge."""
    # RFC 7636 requires 43..128 chars from [A-Z a-z 0-9 - . _ ~]; 32 random bytes -> 43 base64url chars
    verifier = base64url_nopad(secrets.token_bytes(32))
    challenge = base64url_nopad(hashlib.sha256(verifier.encode("ascii")).digest())
    return verifier, challenge


def verify_pkce_s256(code_verifier: str, stored_challenge: str) -> bool:
    """Server side: reject out-of-spec verifiers and compare S256 digest in constant time."""
    if not (43 <= len(code_verifier) <= 128):
        return False
    computed = base64url_nopad(hashlib.sha256(code_verifier.encode("ascii")).digest())
    return hmac.compare_digest(computed, stored_challenge)

Keep three details exact:

  • No padding (=): Standard base64 adds = padding; base64url for PKCE must strip it (rstrip(b"=")), or valid verifiers will fail comparison across libraries.
  • Minimum entropy: Generate at least 32 random bytes (256 bits) so code_verifier is 43 base64url characters—never hash a predictable timestamp or user ID.
  • Constant-time equality: Always use hmac.compare_digest (or subtle::ConstantTimeEq in Rust) rather than ==.

Six PKCE bugs that break security or real clients

1. Accepting code_challenge_method=plain

RFC 7636 defined a legacy plain method where code_challenge == code_verifier. If your server accepts plain, anyone who sees the authorization URL already has the verifier. OAuth 2.1 requires S256 only—reject plain and reject missing code_challenge outright.

2. Letting an authorization code be used twice

An authorization code must be single-use and short-lived (60 seconds is plenty). Burn it atomically in the database (UPDATE ... WHERE consumed_at IS NULL RETURNING ...) so two concurrent /oauth/token requests cannot both succeed. If a burned code is replayed, revoke any tokens already issued from it.

3. Skipping exact redirect_uri matching

Validate that the redirect_uri sent at /oauth/token matches the exact redirect_uri used at /oauth/authorize byte-for-byte—and never allow wildcard or prefix matching on registered redirect URIs (except localhost dynamic ports for native/CLI apps per RFC 8252).

4. Dropping state because “we already use PKCE”

PKCE stops code interception; it does not replace CSRF protection on the client’s callback URL. A client should still generate an unguessable state parameter, store it in the browser session, and verify it on callback so an attacker cannot trick a victim into logging into the attacker’s account.

5. Downgrade attack when PKCE is “optional”

If your server only checks code_verifier when code_challenge was supplied during /oauth/authorize, an attacker can omit code_challenge to bypass PKCE entirely. Require PKCE unconditionally on every authorization-code flow.

6. Edge proxies blocking OAuth discovery on remote MCP servers

When wiring remote MCP clients (like Claude) to an OAuth PKCE server behind Cloudflare, the client first fetches /.well-known/oauth-protected-resource and /.well-known/oauth-authorization-server before calling /oauth/authorize or /oauth/token. On Colophon, Cloudflare’s default Browser Integrity Check blocked Python HTTP clients on those discovery routes with 403 Error 1010 before requests ever hit our origin server (Cloudflare Error 1010 on /mcp and /oauth). Scope Browser Integrity Check off for /.well-known/*, /oauth/*, and /mcp.

Should confidential backend apps still use PKCE?

Yes. Even when a backend server holds a client_secret, OAuth 2.1 recommends PKCE for both public and confidential clients. It adds almost zero complexity (five lines of code) and protects against authorization-code injection attacks even if a client secret is shared across deployments.

For the wider hardening checks around OAuth, tokens, and rate limits, see our API security checklist with concrete tests and how to build an MCP server.

Frequently asked questions

Does PKCE replace client_secret? For public clients (SPAs, mobile apps, CLIs, desktop apps) that cannot keep a secret safely, yes—PKCE replaces client_secret. For confidential server-side apps, use both client_secret (to authenticate the client app) and PKCE (to bind the authorization code to the specific request).

Why must code_verifier be between 43 and 128 characters? RFC 7636 sets 43 characters as the minimum length because 32 random bytes (256 bits of entropy) encode to exactly 43 base64url characters without padding, preventing brute-force guessing against the SHA-256 challenge.

Can I store the code_verifier in localStorage in a browser app? Prefer sessionStorage (or in-memory state if no full-page redirect occurs) and delete the code_verifier immediately after the /oauth/token exchange completes. Never put code_verifier in a URL query string or log it.

Related reading