Cookies, CSRF and cross-window attacks · core
CSRF: how the attack works, step by step
Cross-site request forgery tricks a logged-in user's browser into sending a state-changing request to your site from another site; it works because the browser attaches your cookies automatically, and the attacker never needs to read the response.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Three conditions: (1) a valuable action (change email, transfer money), (2) the server identifies the user only by something the browser sends automatically (cookies, HTTP basic auth, client certs), (3) the attacker can guess every request parameter.
- Classic attack: evil.example hosts a hidden <form method=POST action=https://bank.example/transfer> with amount and account fields and submits it on load. The victim's browser adds the bank cookie; the bank sees a valid session.
- The attacker cannot read the response (same-origin policy), but they do not need to: the side effect already happened.
- GET endpoints that change state are the easiest target: <img src="https://bank.example/logout"> is enough. GET must be safe (no side effects).
- CORS does not stop CSRF: form posts and simple requests (urlencoded, multipart, text/plain) are sent without a preflight. Only non-simple requests (JSON content type, custom headers) are preflighted.
- Not vulnerable: APIs that only accept a bearer token in the Authorization header from JS (the browser never adds it automatically). But that token is then exposed to XSS.
- Variants: login CSRF (log the victim into the attacker's account), and client-side CSRF (your own JS sends a request built from attacker-controlled URL data).
The red pen
Common traps: mistake → fix
Mistake: "CSRF means the attacker steals my cookie"
Fix: the attacker never sees the cookie; the browser sends it for them.
Mistake: "We use POST, so we're safe"
Fix: a cross-site HTML form can send POST.
Mistake: "CORS protects us from CSRF"
Fix: simple requests are sent without any CORS check; CORS only controls reading responses.
Mistake: "HTTPS prevents CSRF"
Fix: the forged request is a normal HTTPS request from the victim's browser.
Easy to hard
Questions interviewers ask, easy to hard
- What is CSRF? Explain it with a banking example.
- Why does the browser send the bank's cookie to a request started by evil.example?
- Does CORS protect against CSRF? Why not?
- Is an API that uses Authorization: Bearer headers vulnerable to CSRF? What is the trade-off?
- What is login CSRF and why does it matter even though the user is not logged in?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.