CSRF (Cross-Site Request Forgery)
A web attack that tricks an authenticated user's browser into sending unintended state-changing requests to a trusted site using automatically attached cookies
Table of Contents
Structure Diagram
What is CSRF (Cross-Site Request Forgery)?
A web attack that tricks an authenticated user's browser into sending unintended state-changing requests to a trusted site using automatically attached cookies. It is a core concept in Auth & Security within Web Dev.
Core Principles
Cross-Site Request Forgery (CSRF) exploits the browser's habit of automatically attaching cookies to every request for a domain. If a logged-in user visits a malicious page, a hidden HTML form can silently submit POST https://bank.example/transfer—and the browser dutifully sends the victim's session cookie along with it.
Whereas XSS steals data by running code inside the trusted site, CSRF abuses the user's ambient cookie authority to trigger unwanted state changes without ever needing to read the response.
Practical Takeaways
- Layer 1 —
SameSite=LaxorStrictcookies: Blocks browsers from sending session cookies on cross-sitePOSTrequests. - Layer 2 — Anti-CSRF tokens & Fetch Metadata: Require an unpredictable per-session token (via hidden input or custom header like
X-CSRF-Token) and validateOrigin/Sec-Fetch-Siteheaders on state-changing routes. - Keep
GETrequests side-effect-free: Never mutate state viaGET, since top-level navigations carrySameSite=Laxcookies.
Notable Examples
- Built-in framework defenses: Django, Rails, Spring Security, and Next.js Server Actions automatically verify CSRF tokens or
Originheaders. - Explicit
Authorizationheader APIs: Because browsers never attachBearerheaders automatically, token-header APIs avoid CSRF (though they still require strong XSS defense).