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.
Step 1: Server generates a cryptographically random CSRF secret when establishing a user session.
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.
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.
[ 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'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 1: Server generates a cryptographically random CSRF secret when establishing a user session.
Step 2: Server delivers the CSRF token to the client via a readable cookie or initial page load payload.
Step 3: Frontend framework intercepts state-changing requests (POST, PUT, DELETE, PATCH) and injects the token into custom HTTP header X-CSRF-Token.
Step 4: Server middleware inspects incoming requests; safe methods (GET, HEAD, OPTIONS) pass through.
Step 5: For mutating requests, server validates the Origin/Referer header and compares the submitted CSRF token against the session secret.
Step 6: If tokens match and origin is valid, the request proceeds; otherwise, returns HTTP 403 Forbidden.
// 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)
);
}- ✕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.
Allowing state-changing operations via GET requests (e.g. GET /api/user/delete?id=12), which bypasses CSRF protections.
Strictly enforce HTTP methods: only allow POST, PUT, DELETE, PATCH for state mutations and guard them with CSRF tokens.
Why does a custom HTTP header like 'X-CSRF-Token' provide inherent CSRF protection in cross-origin browser requests?