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.