CSRF (cross-site request forgery) tricks a logged-in user's browser into sending a request to your site from another site. SameSite cookies stop the browser sending the cookie, and CSRF tokens prove the request came from your own page.
How the attack works: the attacker's page contains, for example, a form that submits itself automatically. The browser attaches the user's cookies, so the server thinks the user made the request. The attacker can't read the response. But the action still happens, like changing an email address or transferring money.
SameSite cookies: SameSite=Lax or Strict stops the browser sending the cookie on cross-site POSTs and subrequests. This blocks most CSRF. Chromium-based browsers (Chrome, Edge) default to Lax when the attribute is missing. Firefox and Safari don't do this by default. So always set it explicitly.
CSRF tokens: the server adds a secret, unpredictable value to each form, or expects it as a custom header. The server checks it on each request. An attacker's page can't read the token, so it can't send it.
Also:
- Keep
GETrequests free of side effects. - Check the
Originheader.
- The browser sends cookies automatically, even with forged requests.
- The attacker can't read responses, but can trigger actions.
SameSite=LaxorStrictstops the cookie being sent cross-site.- Only Chromium-based browsers (Chrome, Edge) default to
Lax, so setSameSiteexplicitly. - The server verifies CSRF tokens or custom headers.
GETrequests should have no side effects.