CSRF — Cross-Site Request Forgery
How attackers trick browsers into making authenticated requests — and why SameSite cookies are the modern defence
Skills taught: websecurity.csrf, websecurity.csrf-tokens, websecurity.samesite-cookies, websecurity.double-submit
How CSRF works
Cross-Site Request Forgery (CSRF) exploits the browser's behaviour of automatically attaching cookies to every request to a domain — even requests initiated from a different site. If a user is logged into bank.com and visits evil.com, a hidden form on evil.com can submit a request to bank.com that the browser sends with the user's session cookie. The bank sees a legitimate-looking request with valid credentials and processes it.
<!-- The attacker hosts this on evil.com -->
<!-- User is logged into bank.com in another tab -->
<!-- Visible attack (with social engineering): -->
<form action="https://bank.com/transfer" method="POST">
<input type="hidden" name="amount" value="10000" />
<input type="hidden" name="to_account" value="attacker_account" />
<button>Click to claim your prize!</button>
</form>
<!-- Silent attack (auto-submits on page load): -->
<form id="csrf" action="https://bank.com/transfer" method="POST" style="display:none">
<input type="hidden" name="amount" value="10000" />
<input type="hidden" name="to_account" value="attacker_account" />
</form>
<script>document.getElementById('csrf').submit();</script>
<!-- The browser sends the request to bank.com WITH the user's session cookie -->
<!-- bank.com sees: authenticated user, valid session, transfer request -->
<!-- bank.com processes the transfer -->
<!-- The user never knew -->
Defence 1 — SameSite cookies (modern, recommended)
// SameSite controls when the browser sends cookies on cross-site requests
// SameSite=Strict: cookie NEVER sent on cross-site requests
// User clicks a link from evil.com to bank.com → no cookie sent
// Breaks OAuth flows, 'Share this article' links, some payment flows
res.cookie('sessionId', token, {
httpOnly: true,
secure: true,
sameSite: 'strict',
});
// SameSite=Lax (default in modern browsers): cookie sent on
// top-level navigation (clicking a link) but NOT on cross-site POST/PUT/DELETE
// Protects against CSRF form submissions while allowing OAuth redirects
// Recommended for most apps
res.cookie('sessionId', token, {
httpOnly: true,
secure: true,
sameSite: 'lax', // ← This alone defeats most CSRF attacks
});
// SameSite=None: cookie always sent (required for embeds, iframes)
// MUST be paired with Secure: true (HTTPS only)
// Vulnerable to CSRF — requires CSRF token if used
res.cookie('sessionId', token, {
httpOnly: true,
secure: true,
sameSite: 'none', // Only use when embedding is required
});
// WHY SameSite=Lax defeats the attack above:
// evil.com submits a form via POST to bank.com
// Browser checks: is this a cross-site POST? Yes.
// SameSite=Lax? Don't attach the session cookie.
// bank.com receives the request with no session → unauthenticated → rejected
Defence 2 — CSRF tokens (older apps, still widely used)
import crypto from 'crypto';
// CSRF token: a random value stored in the session and embedded in forms
// The attacker on evil.com cannot read the token (SOP prevents it)
// So they can't include a valid token in their forged request
// Generate and store token in session
app.use((req, res, next) => {
if (!req.session.csrfToken) {
req.session.csrfToken = crypto.randomBytes(32).toString('hex');
}
next();
});
// Include token in every HTML form
app.get('/transfer', (req, res) => {
res.send(`
<form method="POST" action="/transfer">
<input type="hidden" name="_csrf" value="${req.session.csrfToken}" />
<input name="amount" />
<button>Transfer</button>
</form>
`);
});
// Validate token on every state-changing request
app.post('/transfer', (req, res) => {
const { _csrf, amount, to_account } = req.body;
// Constant-time comparison (prevents timing attacks)
if (!_csrf || !crypto.timingSafeEqual(
Buffer.from(_csrf),
Buffer.from(req.session.csrfToken)
)) {
return res.status(403).json({ error: 'Invalid CSRF token' });
}
// Process the transfer
});
// For SPAs: use the Double Submit Cookie pattern or a custom header
// Custom header approach (axios/fetch always set custom headers, but forms can't):
app.post('/api/transfer', (req, res) => {
// A cross-site form POST cannot set custom headers
// A same-origin fetch() can set custom headers
if (!req.headers['x-requested-with']) {
return res.status(403).json({ error: 'CSRF check failed' });
}
});
Tip: For new apps: SameSite=Lax on session cookies is sufficient CSRF protection. All modern browsers (Chrome 80+, Firefox 79+, Safari 13+) default to SameSite=Lax even if you don't set it explicitly. CSRF tokens are still recommended for defense-in-depth and for apps that need to support older browsers or use SameSite=None. For JSON APIs that only accept Content-Type: application/json — a cross-site form can't set that header — CSRF is not a concern for those endpoints.
Frequently Asked Questions
Does CSRF affect GET requests?
CSRF can technically affect GET requests if they perform state changes (bad practice). An attacker can include an <img src='https://bank.com/delete-account'> tag — the browser GETs the URL with cookies. This is why state-changing actions should NEVER use GET. The HTTP standard says GET should be idempotent (reading data, not changing it). Restrict CSRF defences to POST/PUT/PATCH/DELETE — but also fix any GET endpoints that change state.