CSRF and how cookies cause it

Backend security Junior Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Pick the fix

A cookie-session app has POST /email/change. Which change blocks CSRF best?

Options
Hint 1 of 1

Why does the browser send the cookie at all?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A SameSite=Lax cookies plus a per-session CSRF token checked on the POST

Correct. Two independent layers.

SameSite=Lax stops the browser attaching the cookie to most cross-site POSTs. A token tied to the session is something an attacking page can't read, so a forged form fails even if a cookie gets through.

Why not the others?
  • B Strict CORS rules. Simple cross-site form POSTs don't need CORS approval.
  • C Switching the endpoint to GET. Makes it worse.
  • D A longer session id. The attacker never needs to know it.

30-second answer

Browsers attach cookies to requests to your site even when another site triggers them, so a hidden form on evil.example can POST to /transfer with the victim's session. Defences: SameSite=Lax or Strict session cookies, an anti-CSRF token tied to the session on every state-changing request, checking the Origin header, and never changing state on GET. APIs authenticated by an Authorization header (not cookies) aren't exposed this way, because browsers don't add that header automatically.

Practise saying it · 30 s. No recording, just a timer

Explain CSRF.

Say your answer out loud, then check which of these points you covered:

  • Ambient cookies
  • SameSite
  • CSRF tokens
  • Origin check
  • No state on GET

Deep dive

Double-submit cookie pattern works without server state.

Custom headers like X-Requested-With force a CORS preflight, which another origin can't pass.

CORS doesn't stop CSRF: simple form POSTs are sent without a preflight.

Login forms need CSRF protection too (login CSRF).

Common mistakes

  • Thinking CORS settings block CSRF.
  • State-changing GET endpoints.
  • Tokens not tied to the session.

Senior take & follow-ups

Explain the ambient-cookie problem, then SameSite, tokens, Origin checks and safe GETs.

Follow-up questions

Think of your answer first, then open the hint.

  1. Are bearer-token APIs vulnerable?

    Show hint

    Not to classic CSRF; the browser doesn't attach the token.

  2. What does SameSite=Lax still allow?

    Show hint

    Cookies on top-level GET navigations.

Suggest a fix if something here is wrong or out of date.