Basic

A form from another site

A fake page could post a change to my logged-in user. The browser sends cookies to any form, so the server must check the request came from you.

What you will see

200

About 1 min of reading

Try It

Require a token a cross-site page cannot supply.

1

A forged form without the token is rejected by the server.

curl -s -o /dev/null -w "%{http_code}" -X POST -d 'name=x' https://yoursite/change

Before you run it, say out loud what it will print. Then open the answer.

What it prints
400
2

The real form includes the session token, so it succeeds.

curl -s -o /dev/null -w "%{http_code}" -X POST -d 'csrf=abc123&name=x' https://yoursite/change

Before you run it, say out loud what it will print. Then open the answer.

What it prints
200

Data Flow

A cross-site form carries your session cookie automatically, so the server requires a CSRF token the attacker cannot read, and SameSite is a supporting floor.
1 Cross-site form posts
↓
2 Browser attaches cookie
↓
3 Server needs unreadable token
↓
4 SameSite blocks cookie
Why this works
Prove same origin

A cross-site form gets your cookies automatically, so cookies alone do not prove the request is yours. A CSRF token is a secret the attacker's page cannot read, required in the request body. That is the proof.

SameSite is a floor

SameSite=Lax/Strict stops the browser from sending the cookie cross-site, closing most cases. It is not the whole answer for top-level navigations or older browsers, so keep the token for state-changing requests.

Examples

The forged POST

<form action='https://yoursite/change' method='POST'>

A page on another origin can submit a form to your endpoint. The browser attaches your session cookie, so the change runs.

The token fix

session_token = random()
form needs session_token in the body

Put a random value in the form that a cross-site page cannot read. The attacker cannot copy it, so the forged request fails.

SameSite cookie

Set-Cookie: session=...; SameSite=Lax

SameSite stops the browser sending your cookie on a cross-site POST. It is the cheap first layer under the token.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← The page runs your input
Previous Lesson
The page runs your input
Next Lesson
Comparing without leaking
Comparing without leaking →