Cross-Site Request Forgery (CSRF) is a web security vulnerability that tricks an authenticated user's browser into sending an unwanted, malicious request to a web application on their behalf. Understanding CSRF is essential for building secure web applications and APIs.
CSRF (Cross-Site Request Forgery) is an attack where a malicious website, email, or script causes a victim's browser to perform an unintended action on a trusted site where the user is already authenticated. Because browsers automatically include cookies (including session cookies) with every request, the server cannot easily distinguish a legitimate user action from a forged one. The attack exploits the trust a web application has in the user's browser, not a flaw in the user's machine.
A successful CSRF attack can cause state-changing actions such as transferring funds, changing an email address or password, or deleting account data — all without the victim's knowledge. The attacker does not need to steal credentials; they only need to craft a request that the victim's authenticated browser will send. This makes CSRF particularly dangerous for banking, e-commerce, and any application that manages sensitive user data.
The attacker crafts a malicious page containing a hidden form or image tag that targets a vulnerable endpoint, such as: <img src='https://bank.com/transfer?amount=1000&to=attacker'>. When the logged-in victim visits the attacker's page, their browser silently fires the request and automatically attaches the bank's session cookie. The server sees a valid, authenticated request and processes it, completing the transfer without the user ever knowing.
The most widely used defense is a CSRF token — a unique, secret, unpredictable value generated server-side and embedded in every state-changing form or request. The server validates this token on submission; since the attacker cannot read the victim's page (due to the Same-Origin Policy), they cannot obtain or forge the token. Frameworks like Django, Rails, Laravel, and Spring Security implement this protection automatically.
The SameSite cookie attribute (set to Strict or Lax) instructs browsers not to send cookies on cross-origin requests, providing a strong and increasingly well-supported layer of protection. Checking the Origin and Referer HTTP headers server-side adds a secondary validation layer. Avoid using GET requests for state-changing operations, as they are especially easy to exploit via image tags or links.
JSON APIs that rely solely on cookies are still vulnerable if they accept requests from any origin and do not validate CSRF tokens or the Origin header. SameSite=Lax still permits top-level navigation GET requests, so it does not fully protect GET-based state changes. Always combine SameSite cookies with CSRF tokens or double-submit cookie patterns for defence-in-depth, and never assume a modern browser feature alone is a complete fix.
© RM Full Stack & AI Engineer · All guides · Roadmaps · Open the app