How to Get Cross-Site Request Forgery Right
An attack, known as CSRF, where a malicious site causes a logged-in user's browser to send an unwanted request to another site, such as changing an email address.
Where most projects go wrong
The usual mistakes:
- Disabling CSRF checks to fix errors
- State changes triggered by GET links
- Relying only on referrer checks
- Assuming JSON APIs are immune
What good looks like instead
- Use the framework's CSRF protection on all forms
- Keep GET requests free of side effects
- Set SameSite on session cookies
- Protect API endpoints that use cookie authentication
- Test forms for missing tokens
Why it matters
Any state-changing action protected only by a session cookie can be triggered from another site unless it is defended.
The specs that matter
| Measure | Figure |
|---|---|
| Main defense | anti-CSRF tokens tied to the user's session |
| SameSite cookies | reduce CSRF risk but are not a complete defense on their own |
| Safe methods | GET requests should not change state |
| Frameworks | many include CSRF protection by default |
Knowing when to hand it over
Tip: Bring in help when building custom forms or APIs with cookie-based authentication, or after a security finding.
Where this comes from
- OWASP — Cross-Site Request Forgery Prevention Cheat Sheet
- MDN Web Docs — Cross-site request forgery (CSRF)
The figures and practices above come from the sources listed.
Working on something like this?
We take on Web Design & Development work for teams who want it done once, properly. Tell us what you are building and we will tell you honestly whether we are the right studio for it. Start a project.
Where to go next
Spotted something wrong? Report an error on this page. We correct on the page and say what changed.