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.
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=LaxStrict: 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 requiresSecure. 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.
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
- Never change state with GET requests.
- Combine
SameSitecookies with tokens for defence in depth. - APIs that use an
Authorizationheader 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.
Comments