Skip to content

Web security basics · Part 4 of 10

CSRF and SameSite cookies

Cross-site request forgery tricks a logged-in browser into sending a request you did not intend. SameSite cookies and CSRF tokens stop it.

· 2 min read

securitycsrf

Browsers attach cookies automatically to requests to a site, whichever page triggered the request. Cross-site request forgery (CSRF) abuses this: a malicious page makes the victim's browser send a request to your site, and the cookie makes it look legitimate.

An example

A bank site changes a password with POST /account/password. An attacker's page contains a hidden form that submits to that URL. If the victim is logged in and visits the page, the browser sends the form together with their session cookie.

Defence 1: SameSite cookies

The SameSite attribute controls whether the browser sends a cookie on cross-site requests.

Code
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax
  • Strict: never sent on cross-site requests. Safest, but a link from another site arrives logged out.
  • Lax: sent on top-level navigations that use safe methods like GET, but not on cross-site form posts. A good default.
  • None: always sent, and requires Secure. Only for cookies that truly need cross-site use.

Most modern browsers treat cookies without the attribute as Lax, but set it explicitly.

Defence 2: CSRF tokens

The server includes a random, unpredictable token in each form and checks it on submission. An attacker's page cannot read the token because of the same-origin policy, so it cannot forge a valid request.

Ruby
require "securerandom"
require "openssl"

token = SecureRandom.hex(32)
submitted = token                       # what the form sends back
puts OpenSSL.fixed_length_secure_compare(token, submitted)

Web frameworks generate and verify these tokens for you. Keep that protection turned on, and include the token in AJAX requests too.

Defence 3: check Origin

For state-changing requests, verify that the Origin or Referer header matches your own site.

Rules of thumb

  1. Never change state with GET requests.
  2. Combine SameSite cookies with tokens for defence in depth.
  3. APIs that use an Authorization header instead of cookies are not exposed to classic CSRF, because the browser does not attach that header by itself.

Takeaway

Set SameSite, keep framework CSRF tokens enabled and keep state changes out of GET requests.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.