tezvyn:

Explaining and preventing CSRF in Express

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

Understanding CSRF and the synchronizer-token pattern.

OUTLINE

CSRF abuses a victim's ambient cookies to forge state-changing requests; the server issues an unpredictable token tied to the session, embeds it in forms, and validates it…

WHAT THIS TESTS: Whether you grasp that the browser automatically attaches cookies to cross-origin requests, why that enables forgery, and how the synchronizer token pattern breaks the attack.

A GOOD ANSWER COVERS: CSRF tricks an authenticated user's browser into issuing an unwanted state-changing request to your application. Because session cookies are sent automatically on every request to your domain, a malicious page that auto-submits a form or fires a request to your endpoint inherits the victim's authenticated session, so a transfer or password change executes as them. The classic defense is the synchronizer token: the server generates a cryptographically random token tied to the user's session, stores it server-side (or signs it), and embeds it in each rendered form (a hidden field) or exposes it for inclusion in a custom request header. On every state-changing request the server compares the submitted token against the expected one and rejects mismatches. An attacker's cross-site page cannot read or guess this token due to the same-origin policy. Setting cookies SameSite=Lax or Strict adds defense, and using safe HTTP semantics (no state change on GET) matters too.

COMMON WRONG ANSWERS: Confusing CSRF with XSS; thinking HTTPS prevents it; thinking requiring login prevents it (the victim is already logged in); putting the token only in a cookie the attacker's request would also send. Allowing GET requests to mutate state.

LIKELY FOLLOW-UPS: Why does SameSite help and where does it fall short? Why must state changes not happen on GET? How does the double-submit-cookie variant work? Does CSRF protection matter for token-in-header SPAs?

ONE CONCRETE EXAMPLE: A banking form renders a hidden _csrf field whose value matches the session-bound token. A forged form on evil.com cannot read that token, so its POST arrives with a missing or wrong token and the server rejects it with 403, blocking the forged transfer.

Read the original → cheatsheetseries.owasp.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.