← Study Notes Security


Security

CSRF

Cross-Site Request Forgery tricks a logged-in user's browser into sending an unwanted state-changing request — the browser auto-attaches its cookies — for example a hidden form that transfers money. Defend with anti-CSRF tokens, SameSite cookies and checking the Origin/Referer. Token-in-header APIs are largely immune, since the token is not sent automatically.


Purpose

Cross-Site Request Forgery (CSRF) exploits the browser's habit of attaching cookies automatically: a malicious page silently submits a request to a site where the victim is logged in — transfer money, change email — and the browser helpfully sends the session cookie along. The server sees a perfectly authenticated request the user never intended.

When to Use It

It threatens any state-changing endpoint authenticated by cookies: form posts, account settings, admin actions. APIs authenticated by an Authorization header are largely immune, because nothing attaches that header automatically.

Trade-offs

Modern defaults have blunted it — browsers now treat cookies as SameSite=Lax unless told otherwise — but 'largely blunted' is not 'solved': SameSite=None cookies, GET endpoints with side effects and subdomain trust still leave gaps. Defence in depth remains the standard.

Implementation

Set session cookies SameSite=Lax (or Strict) plus Secure and HttpOnly; require an anti-CSRF token on state-changing form posts; verify the Origin/Referer header server-side; and never mutate state on GET. Cookie prefixes like __Host- harden the cookie itself.