Skip to content
Module 4 of 8Authentication
Estimated time: 20 min

Cross-Site Request Forgery (CSRF)

Ambient browser credentials, SameSite cookie defense, and synchronizer tokens.

Core Concept & Mental Model

CSRF forces an authenticated user to execute unwanted actions on a web application in which they are currently logged in. Because browsers automatically attach cookies with cross-site requests, a malicious site can trigger unauthorized financial transactions, email changes, or state mutations.

Threat Vector & Impact

An attacker hosts `evil.com` containing `<form action="https://bank.com/transfer" method="POST">`. When the victim visits `evil.com`, a script auto-submits the form. The browser includes `bank.com` session cookies, and the bank processes the fraudulent transfer.

Defensive Architecture & Mitigation

Enforce modern `SameSite=Lax` or `SameSite=Strict` cookie policies. Pair with cryptographically random Anti-CSRF Synchronizer Tokens or Custom Request Headers (`X-Requested-With`, `Authorization: Bearer`).

Technical Deep Dive

The SameSite Cookie Revolution

  • SameSite=StrictCookie is NEVER sent in cross-site requests, even when following a link from an external site.
  • SameSite=Lax (Modern Default)Cookie is withheld on cross-site subrequests (images, iframes, POST forms), but sent on top-level safe GET navigations.
  • SameSite=None; SecureCookie is sent across all cross-site contexts, but strictly requires HTTPS.

Anti-CSRF Synchronizer Token Pattern

The server generates a unique, cryptographically random, unpredictable token per session. On form submission or state-changing API calls, the client must submit this token in a header or hidden field. An attacker on evil.com cannot read this token due to SOP.

Interactive Mental Model Simulation

Live Visualizer
VISUALIZATION: CSRF ATTACK
Evil.comUser is not here yet
Bank.com
Valid Session
User is logged into Bank.com (Session Cookie is stored in browser).

Code Implementation & Patching

Vulnerable Code (Exploitable)
// Vulnerable endpoint relying solely on cookies
app.post('/api/account/email', (req, res) => {
  const userId = req.session.userId; // Authenticated via session cookie
  updateEmail(userId, req.body.email); // CSRF Vulnerable: anyone can trigger this!
  res.json({ success: true });
});
Secure Patched Code (Hardened)
// Defense 1: Set SameSite=Lax on Session Cookie
res.cookie('sessionId', sid, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  maxAge: 86400000
});

// Defense 2: Validate Anti-CSRF Token or Custom Header
app.post('/api/account/email', csrfProtection, (req, res) => {
  // Middleware verifies req.headers['x-csrf-token'] matches session token
  const userId = req.session.userId;
  updateEmail(userId, req.body.email);
  res.json({ success: true });
});
Security Analysis & Core Architectural Rule

SameSite=Lax prevents evil.com from attaching the cookie on POST requests. The CSRF token provides defense-in-depth, ensuring cross-site attackers cannot forge the payload.

Test Your Knowledge on Cross-Site Request Forgery (CSRF)

Challenge yourself with realistic scenario questions in the Web Security Arena.

Launch Practice Arena