Skip to content
Back to CurriculumLesson 07 of 30
sessions-cookiesIntermediate

Cross-Site Request Forgery (CSRF): Synchronizer Tokens, Origin Checking & SameSite Nuances

Cross-Site Request Forgery (CSRF) tricks a victim's browser into submitting unauthorized commands to an authenticated web application using automatically attached cookies. Defenses require the Double-Submit or Synchronizer Token Pattern alongside SameSite=Lax/Strict cookies and strict Origin/Referer header verification.

Interactive Visual Concept ExplainerStep-by-Step Educational Simulation
Visual Step-by-Step Concept Explainersessions-cookies
Cross-Site Request Forgery (CSRF): Synchronizer Tokens, Origin Checking & SameSite Nuances
Steps:
Cross-Site Request ForgeryThe Threat
Victim Visits: evil-site.com
Auto-Submit: POST bank.com/transfer?amount=5000
Browser Default: Attaches bank.com session cookie automatically!
Dual Defense ShieldThe Fix
1. SameSite=Lax/Strict: Browser refuses cookie on cross-site POST.
2. CSRF Token: Secret token injected in form; evil site cannot read it (SOP).
Attack defeated: Server returns 403 Forbidden!
Step 1 of 6
Auto-stepping (1x)

Step 1: Server generates a cryptographically random CSRF secret when establishing a user session.

Security Guarantee: Combine SameSite=Lax/Strict cookies with custom X-CSRF-Token headers for robust defense-in-depth.
Why This Architectural Concept Exists

Browsers automatically send cookies on cross-origin requests by default. If evil.com hosts a hidden form submitting POST /api/transfer to bank.com, the user's session cookie attaches automatically. The application must verify that the intent originated within its own legitimate UI.

Intuitive Mental Model

The Bank Letter with a Forged Stamp: If a courier delivers a withdrawal slip with your official bank seal already stamped on the envelope (automatic cookie), the bank must demand an additional secret one-time code only written inside the checkbook (CSRF token) before dispensing cash.

Architectural System TopologyProtocol Diagram
[ evil.com (Attacker Page) ]
       │
       ▼ (1) Auto-submits hidden form: POST https://cosmos.app/api/delete-account
       │     (Browser automatically attaches CosmosApp session cookies!)
       ▼
[ CosmosApp Server PEP ]
       │
       ├── Check 1: Sec-Fetch-Site == 'cross-site' ──► REJECT (Origin Mismatch)
       ├── Check 2: Header 'X-CSRF-Token' missing ──► REJECT (403 Forbidden)
       ▼
[ Attack Neutralized with HTTP 403 ]
CosmosApp Production Milestone

CosmosApp's collaboration features allow users to delete projects via POST /api/projects/:id/delete. To protect against malicious third-party websites triggering this deletion, CosmosApp generates a cryptographic CSRF synchronizer token bound to the user's session, which the React frontend must include in the X-CSRF-Token HTTP header for all mutating requests.

Step-by-Step Execution Sequence
01

Step 1: Server generates a cryptographically random CSRF secret when establishing a user session.

02

Step 2: Server delivers the CSRF token to the client via a readable cookie or initial page load payload.

03

Step 3: Frontend framework intercepts state-changing requests (POST, PUT, DELETE, PATCH) and injects the token into custom HTTP header X-CSRF-Token.

04

Step 4: Server middleware inspects incoming requests; safe methods (GET, HEAD, OPTIONS) pass through.

05

Step 5: For mutating requests, server validates the Origin/Referer header and compares the submitted CSRF token against the session secret.

06

Step 6: If tokens match and origin is valid, the request proceeds; otherwise, returns HTTP 403 Forbidden.

Production Architecture Blueprint
// CosmosApp CSRF Validation Middleware:
import crypto from 'node:crypto';

export function verifyCsrf(req: Request, sessionCsrfSecret: string): boolean {
  # 1. Safe methods do not require CSRF tokens
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return true;

  # 2. Validate Origin Header
  const origin = req.headers.get('Origin');
  if (origin && origin !== 'https://cosmos.app') {
    return false;
  }

  # 3. Verify Custom Header against session secret
  const submittedToken = req.headers.get('X-CSRF-Token');
  if (!submittedToken) return false;

  return crypto.timingSafeEqual(
    Buffer.from(submittedToken),
    Buffer.from(sessionCsrfSecret)
  );
}
Common Architectural Misconceptions
  • ✕SameSite=Lax cookies completely eliminate the need for CSRF tokens (Lax cookies are still sent on top-level GET navigations, and older browsers do not support SameSite).
  • ✕CSRF protection is needed on GET requests (GET requests must be idempotent and should never mutate server state).

Key Architectural Takeaways

  • ✓Combine SameSite=Lax/Strict cookies with custom X-CSRF-Token headers for robust defense-in-depth.
  • ✓Enforce strict Origin and Referer header checking on all state-changing endpoints.
  • ✓Keep all GET requests strictly read-only and idempotent.
Common Architectural Pitfall

Allowing state-changing operations via GET requests (e.g. GET /api/user/delete?id=12), which bypasses CSRF protections.

Production Best Practice Fix

Strictly enforce HTTP methods: only allow POST, PUT, DELETE, PATCH for state mutations and guard them with CSRF tokens.

Interactive Knowledge Check

Why does a custom HTTP header like 'X-CSRF-Token' provide inherent CSRF protection in cross-origin browser requests?