Cross-Site Request Forgery
(CSRF)
CSRF (often pronounced "sea-surf") is an attack that tricks a web browser into executing an unwanted action in an application to which a user is currently logged in.
The "Confused Deputy" Problem
Think of your browser as a deputy. When you log in to your bank, the bank gives your deputy a badge (a cookie). If a malicious site tells your deputy "Go wire money," the deputy obeys and shows the badge automatically. The bank sees the valid badge and processes the theft, not realizing the user didn't intend it.
lock_open Interactive Attack Simulation
Step through a real-world CSRF scenario.
Login to Bank
You log in to your legitimate banking site. The server sets a session cookie in your browser.
The Trap
You visit a malicious site (e.g., via a phishing email) while still logged in.
The Forged Request
The evil site contains hidden code that forces your browser to send a request to the bank.
Unintended Execution
The browser automatically attaches your Bank Cookie. The bank accepts the request.
Logged In. Cookie stored in browser.
Evil.com Page Code:
How to Defend Against It
There are two primary ways to stop CSRF: one implemented by developers (Tokens) and one by browsers (SameSite).
Anti-CSRF Tokens
The most robust defense. A unique secret key is required for every state-changing request.
When a user loads a form, the server embeds a hidden, random token. When the form is submitted, the server checks if the token matches. The attacker cannot read this token from the legitimate page due to Same-Origin Policy, so they can't include it in their forged request.
SameSite Attribute
Browser-level defense. Tells the browser when to attach cookies to cross-site requests.
Test Your Knowledge
Why is a CSRF token effective?
Correct! 🎉
Since the attacker is on a different domain (`evil.com`), the Same-Origin Policy prevents them from reading the HTML of `bank.com` to steal the token.