Why SPAs Are Public Clients
A single-page application ships its entire codebase to the browser as JavaScript, which means any secret embedded in that bundle — including a client_secret — can be extracted by simply opening dev tools. This makes an SPA a public client in OAuth terms, unable to authenticate itself with a shared secret, so it must use the Authorization Code flow combined with PKCE rather than the legacy Implicit flow, which OAuth 2.1 has formally deprecated.
Cricket analogy: It's like a team's game plan being scribbled on a whiteboard visible through the dressing-room window — anyone with binoculars (dev tools) can read it, so you can't rely on it staying secret the way you would a sealed strategy document.
PKCE: Proof Key for Code Exchange
PKCE has the client generate a random code_verifier, derive a code_challenge as BASE64URL(SHA256(code_verifier)), and send only the challenge in the initial /authorize request. When exchanging the authorization code at the /token endpoint, the client presents the original code_verifier, and the authorization server recomputes the hash and checks it matches the challenge it received earlier — proving the token request comes from the same party that started the flow, even without a client_secret, which blocks authorization code interception attacks.
Cricket analogy: It's like a captain sealing a specific fielding plan in an envelope (code_challenge) before the toss, then only opening and reading the actual plan (code_verifier) after winning it — the match referee can confirm the opened plan matches the sealed one without ever needing a separate password.
// Generating PKCE parameters and building the authorize URL (browser)
function base64url(buffer) {
return btoa(String.fromCharCode(...new Uint8Array(buffer)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
async function startLogin() {
const verifierBytes = crypto.getRandomValues(new Uint8Array(32));
const codeVerifier = base64url(verifierBytes);
sessionStorage.setItem('pkce_verifier', codeVerifier);
const digest = await crypto.subtle.digest(
'SHA-256', new TextEncoder().encode(codeVerifier)
);
const codeChallenge = base64url(digest);
const state = base64url(crypto.getRandomValues(new Uint8Array(16)));
sessionStorage.setItem('oauth_state', state);
const authorizeUrl = new URL('https://idp.example.com/authorize');
authorizeUrl.search = new URLSearchParams({
response_type: 'code',
client_id: 'spa-client-id',
redirect_uri: 'https://app.example.com/callback',
scope: 'openid profile email',
state,
code_challenge: codeChallenge,
code_challenge_method: 'S256',
}).toString();
window.location.assign(authorizeUrl.toString());
}Token Storage in the Browser
Storing tokens in localStorage or sessionStorage exposes them to any script running on the page, so a single cross-site scripting (XSS) vulnerability anywhere in the app can exfiltrate every stored token. Keeping tokens purely in memory (a JavaScript variable, lost on page reload) is safer but requires re-authentication on every refresh unless paired with a silent renewal mechanism, which is why the industry has increasingly moved toward the Backend-for-Frontend (BFF) pattern: a thin server component performs the OAuth flow and holds the tokens, giving the SPA only an httpOnly session cookie.
Cricket analogy: Leaving tokens in localStorage is like a team leaving its actual dressing-room key under the doormat where any passerby can find it — the safer BFF pattern is having security hold the key and only issue a temporary wristband to players.
The OAuth 2.0 for Browser-Based Apps best current practice (BCP) recommends the Backend-for-Frontend pattern as the most secure architecture for SPAs: a lightweight confidential-client backend performs the Authorization Code + PKCE exchange and stores tokens server-side, issuing the SPA only an httpOnly session cookie, eliminating token exposure to XSS entirely.
Silent Renewal and Refresh Tokens
Older SPAs used a hidden iframe pointed at the authorization server to silently renew tokens using an existing session cookie, but this technique has been broken by browser privacy features like Safari's Intelligent Tracking Prevention (ITP), which blocks third-party cookies the iframe depends on. Modern SPA architectures instead rely on the refresh_token grant with rotation — a public client is issued a refresh token (often with a shorter lifetime and sender-constrained where possible) that it can exchange for a new access token without a full redirect, or better yet, delegate that responsibility entirely to a BFF.
Cricket analogy: Silent iframe renewal breaking under ITP is like a coach relying on a hidden signal from the boundary rope that the umpires eventually ban — teams had to switch to an openly declared signal system (refresh token grant) that doesn't depend on a hidden channel.
Avoid the Implicit flow (response_type=token) entirely for new SPA development. It returns the access token directly in the URL fragment, exposing it in browser history and referrer headers, provides no refresh token, and has been formally deprecated by OAuth 2.1 in favor of Authorization Code + PKCE.
- SPAs are public clients that cannot securely hold a client_secret, since their JavaScript is fully readable by end users.
- Authorization Code flow with PKCE is the required approach; the Implicit flow is deprecated under OAuth 2.1.
- PKCE uses a code_verifier/code_challenge pair to bind the token exchange to the party that started the flow.
- localStorage and sessionStorage are vulnerable to XSS-based token theft; in-memory storage is safer but not persistent.
- The Backend-for-Frontend (BFF) pattern is the current best practice: a server holds tokens, the SPA gets only a session cookie.
- Hidden-iframe silent renewal is broken by modern browser privacy features like Safari ITP blocking third-party cookies.
- Refresh token rotation, ideally proxied through a BFF, replaces iframe-based silent renewal in modern architectures.
Practice what you learned
1. Why is a single-page application treated as a public OAuth client?
2. What does PKCE add to the Authorization Code flow for public clients?
3. What is a major risk of storing access tokens in localStorage?
4. What does the Backend-for-Frontend (BFF) pattern do differently from a pure client-side SPA?
5. Why has hidden-iframe silent token renewal become unreliable?
Was this page helpful?
You May Also Like
OAuth with OpenID Connect
Understand how OpenID Connect layers standardized authentication — ID tokens, claims, and the UserInfo endpoint — on top of OAuth 2.0's authorization framework.
Implementing OAuth in a Web App
A practical guide to wiring the Authorization Code flow into a server-rendered web application, from callback handling to secure token storage and refresh rotation.
OAuth for Mobile Apps
How native iOS and Android apps should implement OAuth 2.0 per RFC 8252: external user-agents, PKCE, claimed redirect URIs, and hardware-backed token storage.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics