SPA Authentication Challenges and OAuth 2.0 Flows
What you'll learn: Why traditional server-side authentication breaks for SPAs and how to choose the right OAuth 2.0 flow for client-side apps.
The SPA Authentication Problem
Single-Page Applications (SPAs) run entirely in the browser—JavaScript executing in a public, untrusted environment. Unlike server-side apps that can securely store secrets (like session keys or API credentials), SPAs have nowhere to hide sensitive data. Anyone can open DevTools and inspect your code, localStorage, or memory.
Traditional server-side authentication relied on session cookies managed by the backend. But SPAs often call APIs directly from the browser, need tokens to authenticate API requests, and can't safely store client secrets required by older OAuth flows.
OAuth 2.0 Flow Options for SPAs
Implicit Flow (Legacy): Originally designed for SPAs, this flow returns access tokens directly in the URL fragment. Problem: tokens are exposed in browser history, referer headers, and are vulnerable to XSS attacks. This flow is now deprecated.
Authorization Code + PKCE (Recommended): This modern approach adds a cryptographic challenge (PKCE = Proof Key for Code Exchange) to the standard authorization code flow. Think of it like a secret handshake that changes every time—even if an attacker intercepts the authorization code, they can't exchange it for tokens without the original challenge verifier. The SPA generates a random "code verifier," hashes it to create a "code challenge," and proves ownership when exchanging the code for tokens.
Key Takeaway: SPAs cannot securely store secrets, so always use Authorization Code flow with PKCE for authentication—never use the deprecated Implicit flow, and store tokens carefully (preferably in memory or secure httpOnly cookies via a backend-for-frontend pattern).