security CSRF Explained

warning Vulnerability

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.

CSRF Concept Illustration

lock_open Interactive Attack Simulation

Step through a real-world CSRF scenario.

STEP 1

Login to Bank

You log in to your legitimate banking site. The server sets a session cookie in your browser.

STEP 2

The Trap

You visit a malicious site (e.g., via a phishing email) while still logged in.

STEP 3

The Forged Request

The evil site contains hidden code that forces your browser to send a request to the bank.

STEP 4

Unintended Execution

The browser automatically attaches your Bank Cookie. The bank accepts the request.

person
You (Browser)
public_off
Evil.com
account_balance
Bank.com

Logged In. Cookie stored in browser.

How to Defend Against It

There are two primary ways to stop CSRF: one implemented by developers (Tokens) and one by browsers (SameSite).

vpn_key

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.

Vulnerable
cookie

SameSite Attribute

Browser-level defense. Tells the browser when to attach cookies to cross-site requests.

Lax: The modern default. Cookies are sent if you navigate to the site (e.g., click a link) but NOT on sub-requests (images, frames) or POST requests from other sites. Good balance of security and usability.
Set-Cookie: session_id=xyz; SameSite=Lax
quiz

Test Your Knowledge

Why is a CSRF token effective?