← Back to Frontend, page 2

frontend-0033 · Medium mid

What is CSRF, and how do SameSite cookies and CSRF tokens protect against it?

CSRF is when another site makes the user's browser send a request that carries the user's cookies, so the server thinks it is a real action. SameSite cookies stop the browser from sending the cookie on cross-site requests: Lax allows top-level GET navigation only, Strict allows none, and None allows all but needs Secure. CSRF tokens and origin checks add a second layer.

Full answer

Cookies are attached to a request based on the destination, not on who started the request. If a user is logged in to bank.example and visits evil.example, a hidden form on the evil page can post to bank.example/transfer, and the browser adds the bank cookie. That is cross-site request forgery. The attacker cannot read the response, but the action happens.

Terms: a site is the registrable domain (example.com, with its scheme). A request is same-site when the initiating page and the target share a site. Subdomains of one site are the same site, but different origins.

The SameSite attribute controls cross-site sending:

  • Strict: the cookie is sent only for same-site requests. Following a link from another site starts without the cookie, so the user can look logged out on arrival.
  • Lax: the cookie is also sent on top-level navigations that use a safe method such as GET, but not on cross-site POST, iframes, images or fetch. Chrome treats cookies with no SameSite attribute as Lax by default, though other browsers can differ, so set it explicitly.
  • None: always sent, including cross-site. Requires Secure. Use it for embedded widgets or single sign-on, with care.

Other cookie flags: HttpOnly hides the cookie from JavaScript, Secure sends it only over HTTPS, and __Host- prefix rules tie a cookie to the exact host.

SameSite is not enough alone:

  • A same-site attacker, such as a vulnerable sibling subdomain, still passes.
  • State-changing actions must never use GET.
  • Add a CSRF token: a random value that the server ties to the session and the page sends in a header or form field. A forged request from another site cannot read it. Also check the Origin header on unsafe methods.
  • A custom request header, such as X-Requested-With, forces a CORS preflight for cross-site calls, which helps when CORS is strict.

The test below uses localhost and 127.0.0.1, which are different sites. The server sets three cookies. A form on 127.0.0.1 posts to localhost, and then a link goes there with GET. The server reports the cookies it received.

javascript
import http from 'node:http';

http.createServer((req, res) => {
  if (req.url === '/login') {
    res.setHeader('Set-Cookie', [
      'lax=1; SameSite=Lax; HttpOnly',
      'strict=1; SameSite=Strict; HttpOnly',
      'none=1; SameSite=None; Secure',
    ]);
    return res.end('logged in');
  }
  // /transfer and /whoami report which cookies arrived
  const names = (req.headers.cookie ?? '').split('; ').filter(Boolean).map((c) => c.split('=')[0]).sort();
  res.setHeader('Content-Type', 'text/plain');
  res.end(`${req.method} ${req.url} cookies: ${names.join(',') || 'none'}`);
}).listen(process.env.PORT, () => console.log('listening'));

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. localhost and 127.0.0.1 were used as two different sites. A cross-site form POST sent only the SameSite=None cookie. A cross-site GET navigation sent the Lax and None cookies. All three were sent on a same-site visit. Defaults for third-party cookies differ between browsers, and only Chrome was run.

Key points

  • CSRF abuses the fact that cookies are sent based on the destination.
  • Lax sends cookies on top-level GET navigation only. Strict never sends cross-site. None needs Secure.
  • Set SameSite explicitly because defaults differ between browsers.
  • Use CSRF tokens or Origin checks for state-changing requests.
  • Never change state on GET.

Common mistakes

  • Thinking CORS stops CSRF. A form post is not a CORS request.
  • Relying on the browser default for SameSite.
  • Using SameSite=None without Secure, which browsers reject.
  • Changing data with GET requests, which Lax cookies still allow from links.

Follow-ups

  • Why is a subdomain takeover a problem for SameSite protection?
  • How does a double-submit cookie token work?
  • Which cookie flags protect against XSS theft, and which against CSRF?

Tips

  • Define site versus origin before explaining SameSite.
  • State the three values with one example effect each.