Script Valley
Authentication From Scratch
Security HardeningLesson 5.2

CSRF protection for cookie-based auth

CSRF attack mechanics, synchronizer token pattern, csrf package, double-submit cookie pattern, SameSite cookie attribute, when CSRF applies

When CSRF Attacks Work

CSRF attacks work because browsers automatically attach cookies to cross-origin requests. A malicious page on evil.com can make a POST to yourapp.com, and the browser will include the user's session cookie. If your server trusts the cookie alone, the request succeeds.

SameSite First

Setting sameSite: 'strict' or 'lax' on your session cookie prevents the browser from sending it on cross-site requests. This is the simplest CSRF defense and is supported in all modern browsers. Use it as your first line of defense.

CSRF Token as a Belt-and-Suspenders Defense

npm install csrf
const csrf = require('csrf');
const tokens = new csrf();

// Generate token for a form
app.get('/login', (req, res) => {
  const secret = tokens.secretSync();
  req.session.csrfSecret = secret;
  const token = tokens.create(secret);
  res.json({ csrfToken: token });
});

// Validate on POST
app.post('/auth/login', (req, res, next) => {
  const valid = tokens.verify(req.session.csrfSecret, req.body._csrf);
  if (!valid) return res.status(403).json({ error: 'Invalid CSRF token' });
  next();
}, loginController);

JWTs sent via the Authorization header are not subject to CSRF โ€” the browser never auto-sends custom headers. CSRF only matters for cookie-based auth.

Up next

Input validation and sanitization for auth routes

Sign in to track progress

CSRF protection for cookie-based auth โ€” Security Hardening โ€” Authentication From Scratch โ€” Script Valley โ€” Script Valley