A browser automatically attaches a trusted site’s cookies to every request to it, and cannot tell a request the user made deliberately from one triggered by another page. Attackers exploit this: the server carries out the action even though the user did not decide on it.
What an attack looks like
Victor has logged in to a bank’s site, and his browser holds his session. He then opens a page on another site, which contains an invisible form that submits itself to the bank’s address:
<form method="POST" action="https://bank.example/transfer"> <input name="to" value="attacker.example"> <input name="amount" value="50000"></form><script>document.forms[0].submit()</script>The browser obediently sends the POST along with the session cookie, and to the bank it looks like an ordinary transfer from Victor. The attacker’s page cannot read the response to this cross-origin request because of the same-origin policy, but it does not need to: it is enough that the transfer has already gone through.
How to defend against it
| Defence | How it works |
|---|---|
| CSRF token | the server gives the form a random value and checks it on receipt; a foreign page does not have it |
Cookie with SameSite | Strict stops the browser attaching the cookie to cross-site requests; Lax (the default in Chromium) allows them only on top-level navigation by link; Firefox and Safari do not apply a strict default |
Origin check | the server compares the Origin and Referer headers with its own domain and rejects foreign ones; by default Referer may contain only the origin of the request |
| Custom header in an API | a header such as Authorization or X-CSRF-Token makes the request non-simple: without the server’s permission the browser will not send it |
| Re-entering the password | for dangerous operations, such as a transfer or changing an email address, the server requires the action to be confirmed |
Tokens and APIs
The attack needs authorisation that is attached automatically: a cookie or built-in HTTP authentication. If the client keeps a JWT in localStorage and sends it in the Authorization header, a request cannot be forged from a third-party page: a foreign site does not know the victim’s token, and the Authorization header makes the request non-simple, so without the server’s permission the browser will not send it. In OAuth 2.0 flows, the state parameter protects against CSRF.
Sources
the term is written from these pagesVerified 9 Nov