π
EPISODE 02
SameSite cookies Β· tokens Β· JWT Β· session
CSRF & Authentication
Protect authenticated endpoints from CSRF. Use SameSite cookies, CSRF tokens, and understand the trade-offs between session cookies and JWT tokens.
CSRFauthJWTSameSitecookies
Duration
β± About 2 hours
Level
π Intermediate
Prerequisite
π― node-04
OUTCOME
An auth system that resists CSRF and common token misuse
What you'll learn
- 1Explain CSRF in one sentence
- 2Block CSRF with SameSite=Lax/Strict cookies
- 3Use CSRF tokens when SameSite is not enough
- 4Compare session cookies vs JWT (and pick session for new apps)
1. What is CSRF?
An attacker tricks a logged-in user's browser into firing a request to your site, riding on their cookies. The user did not intend it.
html
<!-- attacker.com -->
<img src="https://yourbank.com/transfer?to=evil&amount=1000">2. SameSite Cookies (First Line of Defense)
text
Set-Cookie: session=abc; HttpOnly; Secure; SameSite=Lax; Path=/- Lax β cookie not sent on cross-site POST (good default)
- Strict β cookie not sent on any cross-site request
- None β only with Secure; needed for embedded contexts
3. CSRF Tokens
Render a per-session random token in your form. The server requires it on submit. The attacker's site cannot read it (Same-Origin Policy).
javascript
// Express + csurf
import csurf from "csurf";
app.use(csurf({ cookie: true }));
app.get("/form", (req, res) => {
res.render("form", { csrfToken: req.csrfToken() });
});
app.post("/transfer", (req, res) => { /* csurf validates automatically */ });4. Session Cookies vs JWT
| Session cookie | JWT (Authorization header) | |
|---|---|---|
| Storage | Server-side (Redis/DB) | Client-side (token contains data) |
| Revoke | Easy (delete the row) | Hard β must check blocklist |
| Size | Tiny | Large (whole user info) |
| XSS | HttpOnly cookie cannot be stolen | localStorage tokens can be stolen |
| Best for | Most web apps | Stateless APIs, mobile clients |
π‘
Default to session cookies for traditional web apps. JWT shines when you cannot rely on cookies (mobile, B2B APIs).
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β