← Lessons

quiz vs the machine

Gold1390

Security

The CSRF Token Defense

How a forged form rides your logged in session, and the secret token that breaks the trick.

5 min read · core · beat Gold to climb

The Attack

Cross site request forgery abuses the fact that browsers attach your cookies to every request to a site, even requests triggered by another site. If you are logged into your bank and visit a malicious page, that page can submit a hidden form to the bank, and your session cookie rides along, authorizing an action you never intended.

The Token Defense

The classic fix is a synchronizer token:

  • The server generates a random, secret CSRF token tied to the session and embeds it in each form.
  • A genuine submission returns the token; the server rejects any request whose token is missing or wrong.
  • An attacker on another origin cannot read the token, so they cannot forge a valid request.

Modern Reinforcements

  • Set session cookies with SameSite so the browser withholds them on cross site requests.
  • Check the Origin or Referer header for state changing requests.
  • Use the token plus SameSite together rather than relying on one alone.

Key idea

CSRF tricks the browser into reusing your session from a hostile origin, and a secret per session token the attacker cannot read, backed by SameSite cookies, lets the server tell genuine requests from forged ones.

Check yourself

Answer to earn rating on the learn ladder.

1. Why does CSRF succeed without a defense?

2. Why can an attacker not forge a valid token?

3. Which cookie attribute reinforces CSRF defense?