Frontend System Design · Lesson 52 of 86 · 5 min
Authentication Flows: OAuth and JWT
This topic tests your understanding of frontend security. You need to explain how a user's identity is managed across requests and with third-party services.
Distinguish Authentication from Authorization
You will be asked this. Get it right.
Authentication (AuthN) is about identity. It's the process of proving you are who you say you are. A username and password form is a classic authentication mechanism. The output is a decision: "Yes, this is User A" or "No, identity not verified."
Authorization (AuthZ) is about permissions. Once authenticated, what are you allowed to do? Can User A read a document? Can they delete it? That's authorization.
In an interview, state the difference clearly. AuthN is the key, AuthZ is which doors the key can open.
The trap: Candidates often use these terms interchangeably. Don't. It signals a lack of precision. Frontend work involves both: you redirect an unauthenticated user to a login page (managing AuthN state), and you hide an "Admin" button from a non-admin user (enforcing AuthZ in the UI). But always state that true authorization happens on the server.
Explain How JWTs Maintain State
A JSON Web Token (JWT) is the standard way to handle authentication in modern frontends. It's a signed, self-contained JSON object encoded as a string.
A JWT has three parts, separated by dots: header.payload.signature.
- Header: Metadata, like the signing algorithm (
alg). - Payload: The data, or "claims." This includes standard claims like
exp(expiration time) andsub(the user's ID), plus any custom data like user roles. - Signature: A hash of the header, payload, and a server-side secret. This is the critical part.
The signature allows the server to verify that the token was issued by a trusted source and that the payload hasn't been tampered with.
Why JWTs matter: They enable stateless authentication. The server doesn't need to store session data in memory or a database. All the information required to identify the user is in the token itself, which the client sends with every request. This scales well, especially in microservice architectures.
The trap: Thinking JWTs are encrypted. They are not. The payload is Base64Url encoded, which is trivially reversible. Anyone who intercepts a JWT can read its contents. Never store sensitive information in a JWT payload. It is for verifiable identity, not for secrecy.
Debate Where to Store Tokens
"You get a JWT from the login endpoint. Where do you store it on the client?" This is a guaranteed question. There is no single perfect answer, only trade-offs.
Option 1: localStorage
- Pro: Simple to implement.
localStorage.setItem('token', ...)andlocalStorage.getItem('token'). It persists across browser tabs and window closures. - Con: Vulnerable to Cross-Site Scripting (XSS). If an attacker can inject JavaScript onto your page (e.g., via a third-party script), they can read the token from
localStorageand impersonate the user. This is a significant risk.
Option 2: HTTP-Only Cookie
- Pro: Secure against XSS. An
HttpOnlycookie cannot be accessed by client-side JavaScript. The browser automatically sends it with every request to the correct domain. - Con: Vulnerable to Cross-Site Request Forgery (CSRF). If a user is logged into your site and visits a malicious site in another tab, that site can make a request to your server, and the browser will helpfully attach the auth cookie. You must implement CSRF protection (e.g., synchronizer tokens) to mitigate this.
The best answer for an interview: Start by acknowledging both options and their trade-offs. For a Single-Page Application (SPA), a common and secure pattern is a hybrid approach:
- Store a short-lived access token (JWT, 15-60 minutes) in memory (e.g., a JavaScript variable). This limits the window for XSS damage.
- Store a long-lived refresh token in a secure,
HttpOnlycookie. This token's only purpose is to get a new access token. - When the access token expires, your API client (or an interceptor) silently uses the refresh token to fetch a new access token and retries the original request. The user sees nothing.
This approach combines the XSS resistance of HttpOnly cookies for the most valuable token (the refresh token) with the CSRF immunity of in-memory tokens for API requests.
Diagram the OAuth 2.0 Flow
OAuth 2.0 is not authentication. It is a framework for delegated authorization. It lets a user grant a third-party application limited access to their resources without sharing their credentials. "Sign in with Google" is OAuth.
For SPAs, the standard flow is the Authorization Code Flow with PKCE. You need to be able to walk through this. PKCE (Proof Key for Code Exchange) is a security extension that prevents an attacker from intercepting the authorization code and using it.
Here is the flow:
Your role as a frontend developer is to implement steps 1, 3, 4, and 6.
- Generate a
code_verifierand acode_challenge. Redirect the user to the auth server with the challenge. - On your callback page, get the
authorization_codefrom the URL. - Send that code, along with the original
code_verifier, to the auth server's token endpoint. - Receive the access token and store it. Now you can make authenticated requests to the resource server.
Implement an API Interceptor for Tokens
Once you have a token, you must send it with every protected API request. The standard is to use the Authorization header with the Bearer scheme.
Doing this manually for every fetch call is error-prone. A better approach is to use an interceptor pattern, which automatically attaches the token to outgoing requests and can handle token refresh logic.
This example shows a wrapper around fetch. In a real app, you'd use the interceptor feature of a library like Axios, or build a more robust wrapper.
// Assume getToken() retrieves the token from memory or storage.
const getToken = () => window.sessionStorage.getItem('accessToken');
// Assume refreshToken() handles the refresh flow and returns a new token.
const refreshToken = async () => {
// In a real app, this would make a POST request to /refresh_token
// using the HttpOnly refresh token cookie.
const newAccessToken = 'new-refreshed-jwt-from-server';
window.sessionStorage.setItem('accessToken', newAccessToken);
return newAccessToken;
};
async function authenticatedFetch(url: string, options: RequestInit = {}) {
let token = getToken();
const headers = new Headers(options.headers);
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
let response = await fetch(url, { ...options, headers });
if (response.status === 401) {
try {
const newAccessToken = await refreshToken();
headers.set('Authorization', `Bearer ${newAccessToken}`);
// Retry the original request with the new token
response = await fetch(url, { ...options, headers });
} catch (refreshError) {
// Handle refresh failure: redirect to login, etc.
console.error("Session expired. Please log in again.");
window.location.href = '/login';
return response; // Or throw an error
}
}
return response;
}
// Usage:
// const userProfile = await authenticatedFetch('/api/profile').then(res => res.json());
This demonstrates the complete lifecycle: attach, send, detect expiration (401), refresh, and retry. This is what interviewers want to see.
Try it
Write a function that takes a JWT string as input. Without using a library, decode its payload and check if the token is expired based on the exp claim. The exp claim is a Unix timestamp (seconds since epoch). Remember that the payload is the second part of the token string and is Base64Url encoded.
Next: Global Error Boundaries in React
Lock it in — apply this lesson under interview conditions.