Concept Explanation
Imagine you are logged into your bank. You then visit a "Funny Cat Pictures" website. The cat website has a hidden button that, when you click it, sends a request to your bank: "Transfer $1,000 to the attacker." Because you are already logged in, your browser automatically sends your login cookies. The bank thinks YOU sent the request.
The key insight: the attacker never sees your cookie and never reads the response. They do not need to. They only need your browser to send an authenticated request. It is forged authority, not stolen data.
XSS and CSRF are opposites worth keeping straight:
| XSS | CSRF | |
|---|---|---|
| Attacker runs code | On your site | On their site |
| Needs your cookie value | Yes, it steals it | No, the browser attaches it |
| Fixed by | Escaping output | Proving intent |
Syntax or Core Structure
The attack, in full
<!-- On evil-cats.com. No JavaScript required. -->
<form action="https://bank.com/transfer" method="POST" id="f">
<input type="hidden" name="to" value="attacker" />
<input type="hidden" name="amount" value="1000" />
</form>
<script>document.getElementById('f').submit();</script>
The defense in Express
// 1. Cookies that refuse to travel cross-site
app.use(session({
cookie: { httpOnly: true, secure: true, sameSite: 'lax' }
}));
// 2. A token the attacker's page cannot read
app.use(csrfProtection);
app.get('/form', (req, res) => res.render('form', { token: req.csrfToken() }));
The Defense: CSRF Tokens
The server gives your website a "Private Key" (the Token). Every time you send a request (like transferring money), you must include this key. The "Cat Website" doesn't have the key, so the bank will reject their fake request.
Why can't the attacker read it? Because the Same-Origin Policy stops JavaScript on evil-cats.com from reading the HTML of bank.com. They can send blind requests, but they cannot see what came back.
Real World Example
SameSite Cookies: Modern browsers now default to SameSite=Lax, which prevents cookies from being sent on "Cross-site" requests. This has made many old CSRF attacks impossible!
But Lax is not a complete fix. It still allows cookies on top-level GET navigations, so any state-changing endpoint reachable by GET remains exposed. That is one more reason GET must never modify data.
Common Mistakes
- Using GET for state changes. A
/delete?id=5endpoint can be triggered by an<img src>tag on any page on the internet. - Storing the token in a cookie alone. If the cookie is the only check, the browser sends it automatically and you have proven nothing. The token must arrive in a place only your own page can fill: a header or a form field.
- Assuming an API is immune because it returns JSON. If it accepts
application/x-www-form-urlencodedor reads cookies for auth, a plain HTML form can reach it. - Relying on
Originalone. Some older clients and privacy tools strip it, so treat a missingOrigincarefully rather than as a pass.
Best Practices
- Set
SameSite=Lax(orStrictfor pure first-party apps) plusHttpOnlyandSecureon every session cookie. - Add a CSRF token for anything cookie-authenticated that changes state. Belt and braces.
- Prefer
Authorization: Bearerheaders over cookies for APIs. Headers are not sent automatically, so CSRF largely evaporates. - Verify
Originon the server as a cheap second layer. - Re-authenticate for the truly dangerous actions: password change, email change, large transfers.
Practice Exercises
- The Token Flow: Draw a diagram showing how a server generates a token, the client stores it, and the client sends it back.
- The Header Check: Research why checking the
RefererorOriginheader is a good (but not perfect) defense against CSRF. - The Helmet: Research the
helmetpackage for Express and list 3 security headers it adds automatically.