CSRF
CSRF (cross-site request forgery) is tricking a logged-in browser into sending a cookie-authenticated request the user did not mean to make. The other site cannot read the response; it only needs the request to succeed.
Detailed Explanation
Cookies are attached to requests by the browser based on the URL, not based on which page initiated them (with SameSite as a brake). If https://bank.example stores a session cookie, then https://evil.example can include <form action="https://bank.example/transfer" method="POST"> and auto-submit. The browser sends the cookie. The bank thinks the user posted.
fetch from evil to bank is blocked from reading by CORS, but a form POST or a simple GET image is not a CORS read. State-changing GET is especially bad: <img src="https://bank.example/transfer?to=evil">.
Defences, stacked:
SameSite=LaxorStrictcookies: Lax sends cookies on top-level GET navigations, not on most cross-site POSTs. This killed a lot of CSRF.SameSite=None(embedded widgets) needs extra defences.- CSRF token: a random value in a cookie the JS can read or in the HTML, and a matching header (
X-CSRF-Token) that evil cannot set on a simple form (custom headers trigger preflight and are not sent by a basic form). - Same-origin only APIs plus
Origin/Refererchecks on the server for cookie-auth mutations. - Do not use GET for mutations.
Bearer tokens in Authorization set by your JS are not sent automatically to evil's form, so they are not CSRF'd the same way. They have XSS problems if stored in localStorage.
What it costs you: a token dance on every form, and a false sense of safety if you set SameSite=None for a marketing iframe and forget the token.
Reach for SameSite plus tokens on cookie sessions. Reach for Authorization headers on SPAs that already do not use cookies for auth. Reach for both if you have cookie auth and cross-site embeds.
Code Examples
async function transfer(to, amount, csrfToken) {
const res = await fetch("/api/transfer", {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken,
},
body: JSON.stringify({ to, amount }),
});
if (!res.ok) throw new Error(`http ${res.status}`);
}<!-- Evil page: classic CSRF. SameSite=Lax blocks most of these POSTs. -->
<form action="https://bank.example/transfer" method="POST">
<input type="hidden" name="to" value="evil" />
</form>Common Gotchas
Cookie-auth + state-changing GET is CSRF with an image tag
mutations must be POST/PUT/PATCH/DELETE and checked.
CORS does not stop form POST
it only stops JS from reading the response.