← Lessons

quiz vs the machine

Gold1420

Frontend

CSRF Protection Deep

Why a logged in user can be tricked into submitting requests and how tokens and SameSite cookies stop it.

6 min read · core · beat Gold to climb

What it is

Cross site request forgery tricks a logged in user browser into sending an unwanted authenticated request. Because the browser attaches cookies automatically, the forged request looks legitimate to the server.

How the attack works

  • The victim is authenticated to your site and holds a session cookie.
  • A malicious page submits a hidden form or image request to your endpoint.
  • The browser attaches the cookie, so the server processes the action.

Defenses

  • Synchronizer token: the server embeds a secret token in the form. A forged request cannot know it, so the server rejects the mismatch.
  • Double submit cookie: the token lives in both a cookie and a request value, and the server checks they match.
  • SameSite cookies stop the cookie from being sent on cross site requests.
  • Verify the Origin or Referer header for state changing requests.

Key point

Tokens defend because the attacker can make the browser send a request but cannot read your token from another origin.

Key idea

CSRF abuses automatic cookie sending; defend with unguessable tokens and SameSite cookies so cross origin requests fail.

Check yourself

Answer to earn rating on the learn ladder.

1. Why does a CSRF token stop the attack?

2. What makes a forged request look legitimate to the server?