TExcelTAD
Home › Cybersecurity › CSRF & SameSite Cookies

CSRF & SameSite Cookies

Browsers attach cookies automatically to requests for the site that set them, even when the request is triggered by a different website. Cross-site request forgery (CSRF) abuses this: a malicious page makes the victim's browser send a request to a site where the victim is logged in, and the site can't tell it apart from a real one.

How CSRF works (conceptually)

  1. Alice logs in to bank.example; her browser stores the session cookie.
  2. Later, in another tab, she visits a malicious page.
  3. That page contains a hidden form that auto-submits to https://bank.example/transfer.
  4. Her browser sends the request with her session cookie, and the bank executes the transfer.

The attacker never sees the response or the cookie; they only need the side effect. That's why CSRF targets state-changing actions: transfers, email changes, password changes, deleting things.

Conditions for CSRF:

  • authentication relies on something the browser sends automatically (cookies, HTTP Basic auth, client certificates);
  • the action can be triggered with a predictable request (no secret value the attacker doesn't know).

APIs that authenticate with an Authorization: Bearer header set by JavaScript are not vulnerable in the same way, because another site can't make the browser add that header.

Defence 1: SameSite cookies

The SameSite cookie attribute tells the browser when to send the cookie on cross-site requests:

Value Cookie sent on cross-site requests? Notes
Strict Never Strongest; following a link from email arrives "logged out"
Lax Only on top-level GET navigations Default in modern browsers; blocks cross-site POST forms
None Always (requires Secure) Needed for embedded third-party use; no CSRF protection

The model below shows what a browser does with each setting:

python · try it yourself
def cookie_sent(samesite, same_site_request, method, top_level_navigation):
    if same_site_request:
        return True
    if samesite == "Strict":
        return False
    if samesite == "Lax":
        return method == "GET" and top_level_navigation
    return True   # None

scenarios = [
    ("user clicks a link on the bank's own page", True, "POST", True),
    ("evil site auto-submits a POST form", False, "POST", True),
    ("evil site loads an <img> GET", False, "GET", False),
    ("user follows a link from an email", False, "GET", True),
]

print(f"{'scenario':<44}{'Strict':>8}{'Lax':>6}{'None':>6}")
for label, same, method, top in scenarios:
    row = "".join(f"{'yes' if cookie_sent(v, same, method, top) else 'no':>{w}}"
                  for v, w in [("Strict", 8), ("Lax", 6), ("None", 6)])
    print(f"{label:<44}{row}")
scenario                                      Strict   Lax  None
user clicks a link on the bank's own page        yes   yes   yes
evil site auto-submits a POST form                no    no   yes
evil site loads an <img> GET                      no    no   yes
user follows a link from an email                 no   yes   yes

With Lax, the dangerous cross-site POST arrives without the session cookie, so the bank sees an anonymous request. Note that Lax still sends cookies on top-level GETs, which is one reason GET requests must never change state.

Note: "Same site" means the same registrable domain (app.example.com and api.example.com are the same site). A vulnerable sibling subdomain can therefore bypass SameSite, so it is a strong layer, not a complete fix.

Defence 2: anti-CSRF tokens

The classic defence is a synchronizer token: the server puts an unpredictable token in each form (or sends it to the JavaScript app) and requires it back with every state-changing request. The attacker's page can't read the token (the same-origin policy prevents it), so its forged request fails. A common stateless variant derives the token from the session with an HMAC:

python · try it yourself
import hmac
import hashlib

SERVER_KEY = b"demo-csrf-key-32-secret-bytes!!!"   # DEMO ONLY

def csrf_token(session_id: str) -> str:
    return hmac.new(SERVER_KEY, b"csrf:" + session_id.encode(), hashlib.sha256).hexdigest()

def handle_transfer(request):
    if request["method"] in ("GET", "HEAD", "OPTIONS"):
        return "405 state changes need POST"
    expected = csrf_token(request["cookies"]["session"])
    supplied = request["form"].get("csrf_token", "")
    if not hmac.compare_digest(expected, supplied):
        return "403 CSRF token missing or invalid"
    return f"200 transferred {request['form']['amount']} EUR"

alice_session = "s-7f3a9c"
form_token = csrf_token(alice_session)      # embedded in the real form

real = {"method": "POST", "cookies": {"session": alice_session},
        "form": {"amount": "50", "csrf_token": form_token}}
forged = {"method": "POST", "cookies": {"session": alice_session},   # browser adds the cookie...
          "form": {"amount": "5000"}}                                # ...but no token
guessed = {"method": "POST", "cookies": {"session": alice_session},
           "form": {"amount": "5000", "csrf_token": "0" * 64}}
via_get = {"method": "GET", "cookies": {"session": alice_session}, "form": {"amount": "5000"}}

for name, req in [("real form", real), ("forged", forged), ("guessed", guessed), ("GET", via_get)]:
    print(f"{name:<10} {handle_transfer(req)}")
real form  200 transferred 50 EUR
forged     403 CSRF token missing or invalid
guessed    403 CSRF token missing or invalid
GET        405 state changes need POST

Frameworks do this for you: Django's {% csrf_token %}, Rails' protect_from_forgery, ASP.NET Core's antiforgery tokens, Spring Security's CSRF protection. Keep them enabled.

Defence 3: checking Origin

Browsers add an Origin header (and usually Sec-Fetch-Site) to cross-origin POST requests. A server can reject state-changing requests whose origin isn't on its allow-list:

python · try it yourself
ALLOWED_ORIGINS = ["https://bank.example", "https://app.bank.example"]

def origin_ok(headers):
    origin = headers.get("Origin")
    if origin is None:
        # older clients or same-origin requests without Origin: fall back to Sec-Fetch-Site
        return headers.get("Sec-Fetch-Site") in ("same-origin", "none")
    return origin in ALLOWED_ORIGINS

tests = [
    {"Origin": "https://bank.example"},
    {"Origin": "https://evil.example"},
    {"Origin": "https://bank.example.evil.example"},
    {"Sec-Fetch-Site": "cross-site"},
    {"Sec-Fetch-Site": "same-origin"},
]
for headers in tests:
    print(f"{str(headers):<48} {'allow' if origin_ok(headers) else 'reject'}")
{'Origin': 'https://bank.example'}               allow
{'Origin': 'https://evil.example'}               reject
{'Origin': 'https://bank.example.evil.example'}  reject
{'Sec-Fetch-Site': 'cross-site'}                 reject
{'Sec-Fetch-Site': 'same-origin'}                allow

The exact-match comparison matters: a check like origin.startswith("https://bank.example") would accept https://bank.example.evil.example.

Summary

Use all three: SameSite=Lax (or Strict) session cookies, framework CSRF tokens on every state-changing form or request, and an Origin check. And never let GET requests change state. For really sensitive actions (changing a password or payout account), also ask the user to re-authenticate.

Go further: CSRF: SameSite Cookies and Tokens attacks a forgeable toy bank and layers the defences one by one.

Test yourself

Why does CSRF work at all?

  1. Attackers can read other sites' cookies
  2. Browsers automatically attach a site's cookies to requests triggered by other sites
  3. HTTPS is disabled
  4. Servers trust the Referer header

With SameSite=Lax, is the session cookie sent on a cross-site POST form submission?

  1. Yes
  2. No
  3. Only over HTTP
  4. Only with JavaScript

Why can't an attacker's page simply include the anti-CSRF token in its forged form?

  1. Tokens are encrypted
  2. The same-origin policy prevents it from reading the token from the real site
  3. Tokens change every second
  4. Browsers delete tokens