Skip to content
Web Design & Development

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.

Marcus Adeyemi Technical Director 2 min read 20 views
How to Get Cross-Site Request Forgery Right

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
What to do and what to avoid with cross-site request forgery, side by side
Good practice against the usual mistakes, from the sources listed below.

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

Published figures for Cross-Site Request Forgery
MeasureFigure
Main defenseanti-CSRF tokens tied to the user's session
SameSite cookiesreduce CSRF risk but are not a complete defense on their own
Safe methodsGET requests should not change state
Frameworksmany 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.

All services

The work behind this article, and what it costs.

Marcus Adeyemi

Builds and maintains the web work. Writes about front-end architecture, performance, accessibility and the unglamorous parts of keeping a site alive.

Keep reading

More in Web Design & Development