CSRF Prevention Deep Dive
Prevent Cross-Site Request Forgery with tokens, SameSite cookies, and Origin checking.
What you'll learn
- CSRF attack mechanism and exploit conditions
- Synchronizer token pattern
- Double-submit cookie pattern
- SameSite cookie attribute and Origin validation
Concept
CSRF Prevention Deep Dive
Cross-Site Request Forgery (CSRF) tricks an authenticated user into making an unwanted request to a site where they are logged in.
Attack Mechanism
User is logged into bank.com (has session cookie). They visit evil.com which POSTs to bank.com/transfer. Browser sends cookie automatically. If bank.com doesn't verify origin, transfer goes through.
Synchronizer Token
Server generates random CSRF token, embeds in form as hidden field, stores in session. On submit, compare form token with session token. Attacker can't read token due to SOP.
Double-Submit Cookie
Server sets CSRF cookie with random value. Client reads cookie and includes as X-CSRF-Token header. Server compares cookie with header. No server-side session storage needed.
SameSite Cookies
Set-Cookie: SameSite=Strict prevents cookie in cross-site requests. Lax allows top-level GET. Modern browsers default to Lax. Combine with tokens for defense in depth.
Example
const crypto = require('crypto');
function genToken() { return crypto.randomBytes(32).toString('hex'); }
function validateCSRF(req) {
const h = req.headers['x-csrf-token']; const c = req.cookies['csrf-token'];
if (!h || !c || h.length !== c.length) return false;
return crypto.timingSafeEqual(Buffer.from(h), Buffer.from(c));
}
function csrfMW(req, res, next) {
if (req.method === 'GET') return next();
if (!validateCSRF(req)) return res.status(403).json({error:'Invalid CSRF token'});
next();
}
const token = genToken();
console.log('Token:', token.substring(0, 16) + '...');
const req = {method:'POST', headers:{'x-csrf-token':token}, cookies:{'csrf-token':token}};
const res = {status(c){console.log('Status:',c);return this;}, json(d){console.log(d);}};
csrfMW(req, res, () => console.log('CSRF valid'));
genToken creates a random token. Client sends as custom header; server compares with cookie using timingSafeEqual. SameSite=Strict adds defense.
Try it
- Hash Generator
CSRF tokens use cryptographic randomness - see how secure tokens are generated.
Common mistakes
The mistake
Relying only on SameSite cookies without a token.
The fix
SameSite=Lax allows top-level GET, which could be exploited. Use both SameSite and tokens.
The mistake
Comparing CSRF tokens with === instead of timing-safe.
The fix
String comparison leaks timing info. Use crypto.timingSafeEqual.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.