← Back to Glossary
Security Glossary

Cross-Site Request Forgery (CSRF) Tokens

Code Security

Cross-Site Request Forgery is an attack that tricks a user's browser into making unwanted requests to a web application where they are already authenticated. CSRF tokens are the primary defense against this. Here is how it works: when your application serves a form or page, it includes a unique, unpredictable token, a random string generated server-side and tied to the user's session. When the user submits the form, the token is sent back with the request. Your server verifies that the token matches what it issued. A malicious website cannot access or guess this token, so any forged request from an attacker's page will be missing the correct token and be rejected. Modern frameworks like Next.js, Django, and Rails include CSRF protection built in. Additional defenses include SameSite cookie attributes (which prevent cookies from being sent with cross-origin requests) and checking the Origin and Referer headers on incoming requests.

Why It Matters

CSRF attacks exploit the trust that a web application has in the user's browser. If you are logged into your bank and visit a malicious website, that site can contain a hidden form that submits a money transfer request to your bank, and your browser will dutifully include your authentication cookies with the request. Without CSRF protection, the bank's server has no way to distinguish between a legitimate transfer you initiated and a forged one the attacker triggered. The attack requires no special access or technical sophistication on the attacker's part, just a webpage with a hidden form or image tag. Any application that performs state-changing operations (transfers, account updates, data deletion, permission changes) based on cookie-authenticated requests is vulnerable if it does not implement CSRF protection.

What Happens Without It

In 2008, a CSRF vulnerability in the popular UTorrent BitTorrent client's web interface allowed any website to exploit it by sending forged requests that could change settings, add torrents, or even execute commands on the user's computer. The attack required nothing more than visiting a malicious webpage. Netflix experienced a CSRF vulnerability in 2006 that allowed attackers to change user account settings, add movies to queues, and modify shipping addresses, all by embedding forged requests in a website that Netflix users visited. ING Direct, a major online bank, had a CSRF vulnerability that allowed attackers to initiate unauthorized wire transfers from customer accounts simply by luring the customer to a webpage containing a hidden form. These attacks succeeded because the applications relied solely on cookies for authentication without any mechanism to verify that the request actually came from their own interface.

Every app I build includes CSRF protection by default.

or hi@mikelatimer.ai