Every frontend app that lets users "Sign in with Google" or "Connect your GitHub account" implements OAuth 2.0 under the hood. OpenID Connect adds the identity layer — who the user is, not just what they can access. Understanding these protocols is essential for any frontend engineer building apps with third-party auth or exposing APIs.
FrontendSecurityProtocolOAuthOIDC
What Are We Building?
A complete authentication and authorization integration for a single-page application. The system lets users authenticate via an external Identity Provider (Google, GitHub, Auth0), obtains scoped access tokens, and uses them to call protected APIs. It handles the full lifecycle: login redirect, token exchange, token refresh, and secure logout.
OAuth 2.0 is the industry-standard protocol for authorization. It lets a client application access resources on behalf of a user without ever seeing the user's password. OpenID Connect (OIDC) sits on top of OAuth 2.0 and adds authentication — a verifiable assertion that the user is who they claim to be.
The integration has three surfaces: the auth client (handles PKCE, token exchange, refresh), the API client (attaches tokens to requests, handles 401s), and the UI layer (sign-in button, redirect callback, profile display, logout). Here is what the React integration looks like from the consumer's perspective:
example.tsx
<AuthProvider>
<App>
{isAuthenticated ? <Dashboard /> : <SignInButton />}
</App>
</AuthProvider>
// Inside a component:
const { user, login, getAccessToken } = useAuth();
return <button onClick={login}>Sign in with Google</button>;
The provider wraps the entire app. Components read auth state through useAuth(). The heavy lifting — PKCE generation, token exchange, refresh deduplication — happens inside the auth client, invisible to the UI.
1 · Requirements & Scoping
Before writing any auth code, clarify what the system must — and must not — do. These are the questions I would ask in a system design interview.
Functional requirements
User authentication: Users can sign in using an external Identity Provider (Google, GitHub, or a custom OIDC provider). The app learns the user's identity (name, email, avatar).
Token-based API access: The app can call backend APIs using an access token. The token is attached to every request as an Authorization: Bearer header.
Silent token refresh: When the access token expires (usually after 15-60 minutes), the app refreshes it without requiring the user to re-authenticate.
Secure logout: The app clears all tokens and optionally revokes them at the Authorization Server.
Scope management: The app requests only the scopes it needs (e.g., openid profile email) and respects the granted scopes.
Non-functional requirements
Security: Tokens must be stored securely. Access tokens in memory only. Refresh tokens in httpOnly cookies. No token leakage via XSS.
No password access: The app never sees the user's password. Authentication happens at the Identity Provider's domain.
Resilience: If the refresh token is revoked or expired, the app gracefully redirects to login.
Minimal bundle impact: The auth integration should not add more than ~5 KB gzipped. No heavy crypto libraries — use the Web Crypto API for PKCE.
Single sign-on (SSO): If the user is already authenticated at the IdP (e.g., signed into Google), the login flow should complete without re-entering credentials.
Tip
I intentionally scoped out server-side session management. The app is a pure SPA — the backend validates tokens on each request but does not maintain server-side sessions. This is the recommended pattern for APIs that serve multiple clients (web, mobile, third-party). If you need server-side sessions, add a session cookie on top — but that is an orthogonal concern.
2 · Architecture & High-Level Design
OAuth 2.0 defines four roles that interact in every auth flow. The key architectural decision is how these roles communicate and which grant type to use. The wrong choice — using the Implicit Flow instead of PKCE — is the single most common security mistake in SPA auth.
Figure 1 — OAuth 2.0 defines four roles. The Resource Owner authorizes the Client to access resources on the Resource Server via tokens issued by the Authorization Server. SPA clients must use Authorization Code + PKCE.
The Four Roles
Resource Owner: The user who owns the data. They prove their identity by authenticating at the Authorization Server's login page.
Client: The application requesting access. This is our SPA. A public client cannot securely store a client secret (the browser exposes everything).
Authorization Server: Issues tokens after successful authentication. Acts as both the auth endpoint (/authorize) and token endpoint (/token). Examples: Auth0, Google Identity Platform, AWS Cognito, Keycloak.
Resource Server: Hosts the protected resources. Validates access tokens on every request. This is your API gateway.
Grant Type Decision
OAuth 2.0 defines several grant types. For a browser-based SPA, there is only one correct choice. Here is how I evaluated the options:
Implicit Flow (deprecated)
Returns access_token directly in the URL fragment. Removed from OAuth 2.1. No refresh_token. Security issues with URL leakage and token injection.
Authorization Code Flow
Returns an intermediate code, exchanged server-side for tokens. Requires a client_secret. SPA cannot keep a secret — the browser leaks it.
Authorization Code + PKCE (chosen)
Same as auth code, but uses a cryptographic challenge instead of a client secret. The only secure choice for SPAs. Mandated by OAuth 2.1.
Key Insight
The OAuth Security BCP (Best Current Practice) and OAuth 2.1 draft both mandate PKCE for all public clients. There is no defensible reason to use the Implicit Flow in 2024. Every major Identity Provider — Google, GitHub, Auth0, Cognito, Keycloak — supports Authorization Code + PKCE. If your IdP doesn't, switch IdPs.
Why not a BFF pattern?
A Backend-for-Frontend (BFF) proxy adds a server-side token exchange layer between the SPA and the AS. The SPA never sees the tokens — the BFF manages them. This is more secure but introduces server infrastructure. For this design, I chose a client-side flow because it is simpler, works with static hosting (CDN + S3), and the security of PKCE + httpOnly cookies is sufficient for most applications. Add a BFF only if you need token rotation, centralized audit logging, or support for confidential clients.
3 · Data Model & State Shape
The auth system revolves around three token types and two ephemeral values. Understanding their structure and lifecycle is critical to implementing the protocol correctly.
Figure 3 — JWT structure. Three base64url-encoded segments separated by dots. The signature is verified using the Authorization Server's public key, published at the JWKS endpoint. Claims are the assertions carried inside the payload.
Token Types
Access Token: A short-lived credential (15-60 minutes) that proves authorization to access specific resources. Almost always a JWT containing the user's identity (sub), scopes, issuer, and expiry. Sent with every API request via Authorization: Bearer.
Refresh Token: A long-lived credential (days to months) used to obtain new access tokens. Stored in an httpOnly cookie. Never exposed to JavaScript. Revocable by the AS if compromised. Opaque to the client — usually not a JWT.
ID Token (OIDC): A JWT that authenticates the user. Contains claims about the user's identity (name, email, profile picture). Does not authorize API access — only proves that authentication occurred at a specific time. Verified on the client side using the AS's JWKS.
Ephemeral Values (Client-Side Only)
code_verifier: A random string generated by the SPA before the login redirect. Stored in sessionStorage. Used once during token exchange, then discarded. 32 bytes (256 bits) of entropy from crypto.getRandomValues().
state: A random string for CSRF protection. Stored in sessionStorage alongside the verifier. Verified when the AS redirects back. Without it, an attacker can forge an auth response.
JWT Registered Claims
Claim
Name
Purpose
sub
Subject
Unique identifier for the user at the issuer
iss
Issuer
URL of the Authorization Server that issued the token
aud
Audience
Intended recipient (your client_id)
exp
Expiration
Unix timestamp when the token expires
iat
Issued At
Unix timestamp when the token was issued
scope
Scope
Space-separated list of granted permissions
nonce
Nonce
OIDC: replay protection. Must match the value sent in the auth request
Note
Never store access tokens in localStorage. Any XSS vulnerability leaks all tokens. Memory-only storage with periodic refresh (from an httpOnly cookie) is the safest pattern for SPAs. If you must persist sessions across page reloads, use a secure, SameSite httpOnly cookie that the AS renews silently. Auth0's silent auth and AppAuth-JS both implement this pattern.
4 · Interface Definition (API)
The Authorization Server exposes two primary endpoints. The SPA interacts with both during the auth flow. Understanding the contract of each is essential — one wrong parameter and the entire flow fails with a cryptic redirect or CORS error.
Authorization Endpoint — GET /authorize
The SPA redirects the user's browser to this endpoint. The AS authenticates the user, asks for consent, and redirects back with a one-time authorization code. All parameters are in the URL query string:
example.http
GET /authorize?
response_type=code
&client_id=spa-client-123
&redirect_uri=https://app.example.com/callback
&scope=openid+profile+email
&state=xyz789
&code_challenge_method=S256
&code_challenge=9jK3f...
Param
Required
Description
response_type
✓
Must be code for auth code flow
client_id
✓
Public identifier for the SPA, pre-registered at the AS
redirect_uri
✓
Must exactly match a URI registered at the AS
scope
✓
Space-separated scopes. Include openid for OIDC
state
✓
Opaque value for CSRF protection. Verified on redirect back
code_challenge
PKCE
SHA-256 hash of the code_verifier. Required for PKCE
code_challenge_method
PKCE
Must be S256 (plain is not recommended)
Token Endpoint — POST /token
Exchanges the authorization code for tokens. This is a backchannel request from the SPA (via fetch) — not a browser redirect. The request body uses x-www-form-urlencoded. The AS must allow CORS from the SPA origin.
example.http
POST /token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&code=AUTH_CODE_123
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
&client_id=spa-client-123
&redirect_uri=https://app.example.com/callback
Returns the user's profile claims. Called with the access token in the Authorization header. The response is a JSON object with the claims granted by the scope (sub, name, email, picture, etc.). This endpoint is how the SPA gets the user's name and avatar after login.
Publishes the Authorization Server's public keys. The SPA (or more commonly, the API gateway) fetches this to verify the signature of the ID token and access token. The keys are rotated periodically — the kid in the JWT header selects which key to use.
5 · Component Deep Dive — SPA Integration
This section is the "hands-on" part — how to implement the OAuth flow in a React SPA. The implementation divides into five layers: PKCE generation, token exchange, request interceptor, refresh with deduplication, React context, and ID token verification.
5a. PKCE — cryptographic challenge
PKCE (Proof Key for Code Exchange, pronounced "pixie") replaces the client secret with a one-time cryptographic challenge. The SPA generates a random code_verifier, computes a SHA-256 hash as the code_challenge, and sends the hash in the authorize request. When exchanging the code, it sends the original verifier — the AS verifies the hashes match. An attacker who intercepts the auth code cannot exchange it without the verifier.
The crypto.getRandomValues() and crypto.subtle.digest() calls use the Web Crypto API — no library needed. The base64url encoding removes padding (=) and uses URL-safe characters (- and _). The verifier must have at least 32 bytes of entropy per the PKCE RFC.
5b. Token exchange
When the AS redirects back to the SPA with the authorization code, the callback handler reads the code from the URL query string and exchanges it for tokens. This is a fetch call, not a browser navigation — the AS must allow CORS from the SPA origin.
The token exchange must happen from the SPA (via fetch), not from a server. If you proxy through a backend, the backend sees the tokens and could misuse them. The AS's CORS policy should be configured to allow your SPA origin. If you use a backend proxy for security, make sure it does not log the tokens in access logs.
5c. Fetch wrapper with auth header
Every API call needs an Authorization header. A wrapper function centralizes this logic and provides a clean point for error handling. The wrapper also converts a 401 response into a typed error that the caller can catch and handle.
authFetch.tstypescript
function createAuthFetch(getToken: () => Promise<string>) { return async (input: RequestInfo, init?: RequestInit) => { const token = await getToken(); const headers = new Headers(init?.headers); headers.set("Authorization", `Bearer ${token}`); const res = await fetch(input, { ...init, headers }); // Handle 401 — token expired, let caller refresh if (res.status === 401) { throw new TokenExpiredError(); } return res; };}// Usageconst authFetch = createAuthFetch(() => authClient.getAccessToken());try { const res = await authFetch("/api/user/profile"); const data = await res.json();} catch (err) { if (err instanceof TokenExpiredError) { await authClient.refresh(); // Retry with fresh token }}
The getToken callback abstracts where the token comes from. The interceptor does not care about token storage — it just needs a string. This separation lets you swap token strategies (e.g., switch from memory to a BFF proxy) without touching API call sites.
5d. Token refresh with deduplication
Access tokens expire. The refresh flow must handle concurrent token refreshes gracefully — if three API calls trigger a refresh simultaneously, only one refresh request should go out. The pattern is to store a pending promise and deduplicate:
The deduplication pattern stores a pending refresh promise. All callers await the same promise. When it resolves, every caller gets the new token. The 30-second buffer before expiry prevents edge cases where a request starts before expiry but arrives after — a race that causes a spurious 401.
5e. React auth context
The React integration wraps the auth client in a context provider. This gives every component access to the user's identity and auth actions without prop drilling. The provider handles the initialization flow — on mount, it checks whether a session already exists.
AuthContext.tsxtypescript
// React context for auth stateinterface AuthState { user: User | null; isAuthenticated: boolean; isLoading: boolean; login: () => void; logout: () => void; getAccessToken: () => Promise<string>;}const AuthContext = createContext<AuthState | null>(null);function AuthProvider({ children }: { children: React.ReactNode }) { const [user, setUser] = useState<User | null>(null); const [isLoading, setIsLoading] = useState(true); useEffect(() => { // On app load, check if we have a session authClient .silentRefresh() .then((u) => setUser(u)) .catch(() => setUser(null)) .finally(() => setIsLoading(false)); }, []); const login = useCallback(() => { // Redirect to /authorize endpoint const params = new URLSearchParams({ response_type: "code", client_id: CLIENT_ID, redirect_uri: window.location.origin + "/callback", scope: "openid profile email", state: generateState(), code_challenge_method: "S256", code_challenge: /* generated from verifier */ "", }); window.location.href = `https://auth.example.com/authorize?${params}`; }, []); const value = useMemo(() => ({ user, isAuthenticated: user !== null, isLoading, login, logout: () => authClient.logout(), getAccessToken: () => authClient.getAccessToken(), }), [user, isLoading, login]); return ( <AuthContext.Provider value={value}> {children} </AuthContext.Provider> );}function useAuth(): AuthState { const ctx = useContext(AuthContext); if (!ctx) throw new Error("useAuth must be used within AuthProvider"); return ctx;}
Key Insight
The silentRefresh() call on mount is critical — without it, a page reload logs the user out. The AS must support cookie-based session renewal (using the refresh token in an httpOnly cookie) for this to work. Auth0 calls this "silent auth" — it uses an iframe to check the session. Google Identity Services uses a popup. Both achieve the same goal: transparent session recovery.
5f. ID token verification
The ID token is a JWT that proves the user authenticated. The SPA should verify its claims on the client side — signature verification requires the AS's public key from the JWKS endpoint, but the claims validation can be done locally. In practice, most SPAs decode the ID token and validate the nonce and expiry without verifying the signature (the signature is verified by the Resource Server when the access token is used). For maximum security, verify the signature too.
The nonce claim is particularly important — it prevents replay attacks where an attacker intercepts an ID token and uses it to impersonate the user. The SPA generates a nonce before the auth request, stores it in sessionStorage, and verifies it matches when the ID token arrives.
6 · Data Flow & Communication
Let's trace the complete OAuth flow from login to API call, including the PKCE extension and OpenID Connect identity layer. The sequence has six discrete phases, each with a specific purpose.
Figure 2 — Authorization Code Flow with PKCE. The SPA generates a code_verifier and sends the hashed challenge in the initial request. The auth code is exchanged for tokens using the original verifier.
The flow has four logical phases:
Authorization Request
SPA generates PKCE challenge + state, stores the verifier and state in sessionStorage, and redirects the browser to the AS /authorize endpoint with the challenge hash.
User Authenticates & Consents
The AS presents a login page (or SSO session). User authenticates and grants the requested scopes. The AS redirects back to the SPA's redirect_uri with a one-time authorization code.
Token Exchange
SPA reads the code from the URL, retrieves the stored verifier from sessionStorage, and POSTs to /token. The AS verifies the code_verifier against the challenge and returns access, refresh, and ID tokens.
Fetch User Profile
SPA calls GET /userinfo with the access token to get the user's name, email, and avatar. The profile is stored in auth context and exposed through useAuth().
Authenticated API Calls
SPA attaches the access_token to every API request via Authorization header. The Resource Server validates the JWT signature, checks expiry, and returns data. On 401, the refresh flow kicks in.
Token Refresh (as needed)
When the access token expires, the SPA refreshes via POST /token with grant_type=refresh_token. The refresh token is sent in an httpOnly cookie. New tokens arrive, the failed API call retries.
Figure 4 — OpenID Connect extends OAuth 2.0 with an identity layer. The ID Token (a JWT) proves the user authenticated. The UserInfo endpoint returns profile attributes. The scope=openid parameter triggers both.
The scope=openid parameter is the magic switch. Without it, you get pure OAuth — an access token for API access but no identity information. With it, the AS returns an ID token (a JWT proving authentication) and exposes the UserInfo endpoint. The ID token's sub claim links the OAuth authorization to the user's identity — the same sub appears in the UserInfo response and the access token (if it is a JWT).
7 · Performance Optimization
Auth is usually not a performance bottleneck, but there are patterns that prevent it from becoming one — especially under heavy load or when the AS is geographically distant.
Token introspection caching
The Resource Server (API gateway) must validate the access token on every request. If it calls the AS's introspection endpoint for every request, that adds 5-50ms of latency. Solution: cache token validation results. The JWT signature can be verified locally using the AS's public key (from JWKS), which is itself cacheable and rotated infrequently. The JWKS endpoint typically has a Cache-Control: max-age=86400 header — cache it client-side for at least an hour.
Refresh token deduplication
As shown in the refresh interceptor code, multiple concurrent 401s must not trigger multiple refresh requests. The promise deduplication pattern ensures exactly one refresh at a time. All callers wait on the same promise and receive the new token together.
Pre-emptive token refresh
Instead of waiting for a 401, refresh the token before it expires. A setInterval running every 60 seconds checks token expiry and refreshes proactively if the token will expire within the next 5 minutes. This eliminates 401s entirely except for rare long-running operations. The 30-second buffer inisExpired() already catches most edge cases, but a proactive refresh takes it to zero.
ID token verification off the critical path
Verifying the ID token's signature on every render is wasteful. Verify once after token exchange, cache the decoded claims in the auth context, and only re-verify on refresh or page reload. The JWKS public keys are stable and cacheable for hours. The claims validation (expiry, audience, nonce) is cheap and can run on every render if needed — but decode the JWT once and store the result.
Tradeoff table
Strategy
Pros
Cons
Local JWT verification (JWKS)
No AS latency, cacheable keys
Cannot revoke individual tokens immediately
Token introspection (AS call)
Supports immediate revocation
5-50ms added latency per request
Reactive refresh (on 401)
Simple, no timer needed
One failed request per token expiry
Proactive refresh (timer)
Zero 401s, seamless UX
Extra complexity, background timer
8 · Security Considerations
Auth security is the most critical part of the design. A single mistake — storing tokens in localStorage, failing to validate redirect URIs, or omitting the state parameter — can compromise every user. These are the threats I consider non-negotiable to address.
Token storage — memory only for access tokens: Never store access tokens in localStorage or sessionStorage. An XSS vulnerability reads them immediately. Keep the access token in a JavaScript variable (module-level closure). The refresh token goes in an httpOnly, Secure, SameSite=Strict cookie set by the AS — JavaScript cannot read it, so XSS cannot steal it. This is the single most important security rule in SPA auth.
State parameter (CSRF protection): The state parameter in the authorize request must be a cryptographically random value stored in sessionStorage. When the AS redirects back, verify that the returned state matches the stored value. Without this, an attacker can trick the user into linking their account to the attacker's session (login CSRF).
Redirect URI validation (exact match): The AS must validate redirect URIs exactly against a pre-registered allowlist. A partial match (e.g., accepting https://evil.com/?redirect_uri=https://app.com) is an open redirect vulnerability. Always use exact string match. The SPA should also validate that the code came from the expected AS.
Code exchange must be one-time: The authorization code is single-use. If an attacker intercepts it (via a redirect URI trick), the legitimate exchange fails and the attacker's exchange is logged. The AS should also enforce a short code expiry (60 seconds) and bind the code to the client_id and redirect_uri.
PKCE code_verifier entropy: The verifier must have at least 32 bytes of entropy (our implementation uses 32 bytes = 256 bits). Weak entropy lets an attacker brute-force the challenge. The Web Crypto API with crypto.getRandomValues() provides cryptographically strong randomness. Do not use Math.random() — it is not cryptographically secure.
Logout must revoke tokens: A logout button that only clears local state is incomplete. The SPA should call the AS's revocation endpoint and clear the refresh token cookie server-side. Otherwise, the refresh token remains valid and can be used to obtain new access tokens until it expires. The AS should also rotate refresh tokens on each use — if a token is reused, the old one is revoked (this detects token theft).
Warning
The single most dangerous pattern in SPAs is storing access tokens in localStorage. It works during development, passes code review, and breaks only when you get XSSed. By then it is too late — every token is compromised. Use memory-only storage with httpOnly cookie refresh. Auth libraries like AppAuth-JS and OIDC-Client implement this correctly out of the box. Do not roll your own crypto.
9 · Testing Strategy
Auth is notoriously difficult to test because it involves browser redirects, third-party domains, and time-sensitive tokens. The strategy is to isolate the auth client from the UI and test each layer independently, then add a thin E2E layer for the full flow.
Unit tests (auth client logic)
PKCE generation: Test that generateCodeVerifier() returns a base64url string of the correct length (43 characters) and that generateCodeChallenge() produces a SHA-256 hash. Mock crypto.subtle for deterministic results.
Token expiry check: Create an access token with a known exp claim and verify that isExpired() returns the correct value before and after expiry. Test the 30-second buffer boundary conditions.
Refresh deduplication: Call getAccessToken() concurrently from multiple consumers and verify that performRefresh() is called exactly once. Use Promise.all() to create concurrent callers.
ID token claims validation: Create valid and invalid ID tokens (mock the claims) and verify that verifyIdTokenClaims() rejects expired tokens, wrong audience, wrong issuer, and mismatched nonce.
Integration tests (auth fetch + API)
Auth header present: Mock the token provider and verify that every request via authFetch includes an Authorization: Bearer header with the correct token.
401 triggers refresh + retry: Mock the API to return 401 on the first call and 200 on the second. Verify that the refresh flow triggers exactly once and the request retries with the new token.
Failed refresh redirects to login: If the refresh token is expired or revoked, verify that getAccessToken() rejects and the app redirects to the login page. Test both sync and async paths.
E2E tests (browser-based)
Full login flow: Use a test Identity Provider (like Auth0's test tenant) and automate the login flow with Playwright. Verify that the callback page receives tokens, the UserInfo endpoint returns the profile, and the dashboard renders the user's name. This is slow (the redirect takes 2-5 seconds) but irreplaceable.
Page reload preserves session: After login, reload the page and verify the user is still authenticated (silent refresh succeeded). Test with both valid and expired sessions.
Logout clears all state: After logout, verify that API calls return 401 and the user sees the login screen. Verify that the refresh token cookie is cleared.
Token expiry mid-session: Create a short-lived token (1 minute), wait for expiry, and verify that the automatic refresh works and API calls continue without user intervention.
Note
For E2E auth tests, use a dedicated test tenant or Identity Provider. Never test against production auth. If you use Auth0, create a test application with a test user whose credentials are injected via environment variables. Playwright's browserContext.addCookies() can pre-seed the session to skip the login redirect on every test run.
10 · Accessibility & UX
Auth has specific UX and accessibility considerations that are often overlooked in system design discussions. A sign-in flow that is not accessible excludes users who rely on screen readers or keyboard navigation — and since auth is a gate, this means they cannot use the app at all.
Login button
Clear labeling: Use "Sign in with Google" not a bare icon. Screen readers need text content. If you use an icon-only button (like a social icon), include an aria-label.
Loading state: After clicking sign-in, the button should show a spinner and be disabled. The redirect may take 1-3 seconds. Without a loading state, the user may click multiple times, triggering multiple redirects.
Focus management: After redirect back to the SPA, focus should move to the main content, not remain on the now-vanished login button. Use a focus trap or focus restoration pattern.
Callback page
Visible processing: The callback page should show "Completing sign-in..." or a spinner while exchanging the code for tokens. This usually takes 200-500ms. Without it, the page appears blank or frozen.
Error state: If the code exchange fails (e.g., network error, expired code), show a clear error with a "Try again" button that restarts the login flow. Do not leave the user on a blank callback page.
Announce status: Use an aria-live="polite" region to announce auth status changes to screen readers. When the page redirects back from the AS, announce "Sign-in complete" so the user knows they are back in the app.
Session timeout UX
Graceful timeout: Show a modal "Your session will expire in 2 minutes" with a "Stay signed in" button. This prevents mid-operation data loss. Use the ID token's exp and auth_time claims to determine when the session started and when it ends.
Auto-save on expiry: If the session expires during a form fill, save the form state to sessionStorage and restore it after re-authentication. This is particularly important for long-form workflows like checkout or profile editing.
Silent refresh heartbeat: Run a periodic timer that checks token expiry and refreshes proactively. This keeps the session alive as long as the user has the tab open. Stop the timer when the user is idle to reduce load on the AS.
Key Insight
The ID token's auth_time claim tells you when the user last authenticated. Use this to show "You last signed in 3 hours ago" in the profile menu. If auth_time is older than your session threshold, trigger a re-authentication for sensitive actions (step-up auth). This is particularly useful for actions like deleting an account or changing the primary email.
11 · Key Takeaways
SPAs must use Authorization Code + PKCE. The Implicit Flow is deprecated by OAuth 2.1. PKCE replaces the client secret with a cryptographic challenge that does not require server-side storage and prevents interception attacks.
Access tokens in memory, refresh tokens in httpOnly cookies. This is the only storage strategy that survives XSS. localStorage is convenient but catastrophic under attack. Memory-only storage means the token is lost on refresh — this is acceptable because the refresh token (in httpOnly cookie) restores it.
OpenID Connect adds the "who" to OAuth's "what". OAuth authorizes access to resources. OIDC authenticates the user's identity. The scope=openid parameter triggers both ID token issuance and UserInfo endpoint exposure. Without it, you have an access token but no way to identify the user.
JWTs are convenient but require careful validation. Verify the signature (against JWKS), check the expiry, confirm the audience matches your client_id, and validate the issuer. Skip any of these and the JWT is meaningless. The nonce claim prevents replay attacks on ID tokens.
The state parameter is not optional. It is your only defense against CSRF attacks on the auth flow. Use cryptographically random values and verify on every redirect. Store it in sessionStorage alongside the PKCE verifier.
Deduplicate token refreshes. Multiple concurrent 401s must not trigger multiple refresh calls. A single shared promise pattern prevents race conditions and reduces AS load. Combine with a 30-second pre-expiry buffer for maximum reliability.
Test with a real Identity Provider. Unit tests cover the client logic, but only E2E tests against a test tenant catch the full redirect, callback, and session flow. Use Playwright with a persisted auth context to keep tests fast.
OAuth 2.0 and OpenID Connect are not simple. But the complexity is necessary — they solve a hard problem (secure delegation of access across untrusted networks) that every modern application faces. The patterns described here — PKCE, memory-only tokens, deduplicated refresh, React auth context — form a production-grade auth integration that scales from a single-page app to a platform with millions of users.
Key Insight
The key insight is that OAuth is not authentication — it is delegated authorization. OpenID Connect is the bridge that turns "this token can access these resources" into "this user authenticated at this time." Understanding the distinction is what separates a working auth integration from one that has subtle security gaps. Every frontend engineer should know both protocols, not because they implement them from scratch, but because the integrations they build depend on getting the boundary right.