Secure Frontend Authentication: A Sherlockian Blueprint
Elementary, my dear developer. You've outlined the hallmarks of a fortress-like auth system for single-page applications (SPAs): PKCE for code exchange integrity, silent reauth for seamless sessions, rotating refresh tokens for damage control, and ironclad XSS/CSRF guards. I'll deduce and detail a complete, production-ready implementation using modern standards (OAuth 2.0 + OpenID Connect). This assumes an Authorization Server (AS) like Auth0, Keycloak, or Ory Hydra, paired with a frontend in React/Vue/Angular.
We'll use:
- Auth library:
@auth0/auth0-spa-js or oidc-client-js (standards-compliant).
- Storage:
localStorage + in-memory fallbacks (never cookies for tokens in SPAs).
- Threat model: Mitigate interception, replay, injection, and state manipulation.
1. Core Architecture
Frontend (SPA) ↔ AS (OAuth/OIDC)
- PKCE: code_challenge + verifier for auth code flow.
- Tokens: ID/access/refresh (JWTs).
- Flows:
- Login: Redirect to AS → PKCE auth code → Exchange for tokens.
- Silent Reauth: iframe check_session → Refresh if valid.
- Refresh: Rotate refresh_token → New tokens.
- Guards: HttpOnly? No (SPAs can't). Use strict CSP, Content-Security-Policy, and token binding.
Key Principles:
- Never store tokens in cookies (XSS risk).
- Short-lived access tokens (5-15min) + refresh.
- State/nonce for all redirects.
- HTTPS only.
2. PKCE Implementation
PKCE prevents auth code interception (e.g., malicious extensions).
// Generate PKCE pair (S256 recommended)
import { generateCodeVerifier, generateCodeChallenge } from 'auth0-spa-js'; // or crypto.subtle
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier, 'S256');
// Login redirect
const authUrl = new URL('/authorize', AS_DOMAIN);
authUrl.searchParams.set('response_type', 'code');
authUrl.searchParams.set('client_id', CLIENT_ID);
authUrl.searchParams.set('redirect_uri', `${ORIGIN}/callback`);
authUrl.searchParams.set('scope', 'openid profile email');
authUrl.searchParams.set('code_challenge', codeChallenge);
authUrl.searchParams.set('code_challenge_method', 'S256');
authUrl.searchParams.set('state', generateState()); // Random 32+ chars
window.location.href = authUrl.toString();
// Callback: Exchange code
const urlParams = new URLSearchParams(window.location.search);
const { code, state } = urlParams;
if (validateState(state)) { // Compare to stored state
const tokenRes = await fetch('/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: CLIENT_ID,
code,
redirect_uri: `${ORIGIN}/callback`,
code_verifier: codeVerifier, // One-time use!
}),
});
const { access_token, id_token, refresh_token } = await tokenRes.json();
storeTokens({ access_token, id_token, refresh_token });
}
3. Silent Reauth (Iframe Magic)
Renew tokens without popup/redirect using OIDC check_session_iframe.
// Init silent renew
const userManager = new UserManager({
authority: AS_DOMAIN,
client_id: CLIENT_ID,
redirect_uri: `${ORIGIN}/callback`,
response_type: 'code',
scope: 'openid profile',
automaticSilentRenew: true,
silent_redirect_uri: `${ORIGIN}/silent-callback`,
// PKCE auto-enabled
});
// Listen for renew
userManager.events.addSilentRenewError(() => fallbackToPopup());
userManager.events.addUserLoaded(saveTokens);
// Silent check (call periodically or on focus)
await userManager.signinSilent();
Silent Callback (/silent-callback): Minimal HTML with script to userManager.signinSilentCallback() and redirect to app.
Fallback: Popup for browsers blocking iframes (e.g., Safari ITP).
4. Rotating Refresh Tokens
Use → Get new refresh_token on each refresh. Limits blast radius if one leaks.
async function refreshTokens() {
try {
const res = await fetch('/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
client_id: CLIENT_ID,
refresh_token, // Current one
}),
});
const { access_token, id_token, refresh_token: newRefresh } = await res.json();
if (newRefresh !== refresh_token) { // Rotation confirmed
storeTokens({ access_token, id_token, refresh_token: newRefresh });
}
} catch (e) {
logout(); // Revoke on AS too
}
}
// Auto-refresh interceptor (e.g., Axios)
api.interceptors.response.use(
(res) => res,
async (err) => {
if (err.response?.status === 401) {
await refreshTokens();
return api(err.config); // Retry
}
return Promise.reject(err);
}
);
AS Config: Enable refresh_token_rotation and refresh_token_reuse_prevention.
5. XSS/CSRF Guards
SPAs are XSS magnets—sanitize everything.
XSS Protections:
CSRF Protections (Token Binding):
- State Param: Always validate on callback.
- Origin Check: AS validates
redirect_uri.
- CORS: Strict origins on API.
- Double-Submit Cookie (for API calls): Non-HttpOnly cookie with random CSRF token; match header.
// API Request
fetch('/api/data', {
headers: {
'X-CSRF-Token': getCsrfTokenFromCookie(), // Read from doc cookie
'Authorization': `Bearer ${access_token}`,
},
});
Bonus Guards:
- JWT Validation: Client verifies
aud, iss, exp with jwt-decode.
- Token Binding: AS supports
c_nonce or DPoP (RFC 9449).
- Logout:
userManager.signoutRedirect() + revoke refresh on AS.
6. Full Lifecycle
// Init
const userManager = new UserManager({ /* config */ });
await userManager.getUser(); // Restore or silent login
// Protected Route
if (!await userManager.getUser()) {
userManager.signinRedirect();
}
// Logout
await userManager.signoutRedirect({
post_logout_redirect_uri: `${ORIGIN}/logged-out`,
});
fetch('/revoke', { body: `token=${refresh_token}&client_id=${CLIENT_ID}` });
7. Testing & Auditing
- Tools: OWASP ZAP, Burp Suite for interception.
- Scenarios: Network MITM, XSS payload, iframe block, refresh rotation.
- Metrics: Token lifetime <15min; rotation on every use.
This setup withstands nation-state scrutiny. Questions on specifics (e.g., React hooks)? The game is afoot—provide clues! 🔍