Back to 20 Concepts
sessions-cookiesIntermediate

Cross-Site Request Forgery (CSRF): Synchronizer Tokens & SameSite Cookies

CSRF tricks an authenticated user's browser into sending unauthorized POST requests to a vulnerable server. Mitigated via SameSite=Lax/Strict cookie attributes and Synchronizer CSRF Token headers (X-CSRF-Token).

Intuitive Mental Model

The Forged Delivery Check: A scammer mails an invoice pretending to be you because the post office automatically attaches your return address (session cookie). The bank demands a secret one-time transaction stamp (CSRF Token) that only your legitimate banking dashboard knows.

Architecture Blueprint & CodeProduction Standard
// Double Submit CSRF Cookie Pattern:
app.use((req, res, next) => {
  if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(req.method)) {
    const cookieToken = req.cookies['csrf_token'];
    const headerToken = req.headers['x-csrf-token'];
    if (!cookieToken || cookieToken !== headerToken) {
      return res.status(403).json({ error: 'CSRF token mismatch' });
    }
  }
  next();
});

Key Architectural Takeaways

  • SameSite=Lax: Modern browser default that blocks cookies on cross-site POSTs, but permits top-level GET navigation.
  • Synchronizer Token: Random cryptographic token generated per session and verified on all state-changing HTTP mutations.
Common Architectural Pitfall

Relying exclusively on SameSite cookies for CSRF defense on older browsers or mobile webviews that default to SameSite=None.

Production Best Practice

Implement defense-in-depth with custom X-CSRF-Token headers or Origin/Referer header verification.