


We use cookies to improve your experience
We use essential cookies to make our site work. With your consent, we may also use non-essential cookies to improve user experience.
Definition
CSRF (Cross-Site Request Forgery) is a security attack where a malicious website tricks a user's browser into making an unwanted request to a site where the user is authenticated. The attack exploits the browser's automatic inclusion of cookies with every request to a domain.
Imagine you are logged into your bank at bank.com (your browser has a session cookie). You then visit evil.com, which contains a hidden form that automatically submits a POST request to bank.com/transfer?to=attacker&amount=1000. Your browser sends the bank.com session cookie along with this request because it always sends cookies to their matching domain. The bank's server sees a valid, authenticated request and processes the transfer. The attacker never sees your credentials — they just trick your browser into making the request for them.
The most effective defense is CSRF tokens: the server generates a random, unpredictable token for each session and includes it in forms as a hidden field. When the form is submitted, the server verifies the token matches. Since the attacker cannot read the token from another origin (same-origin policy), they cannot forge a valid request. Modern frameworks (Django, Rails, Laravel, Next.js) include CSRF protection by default.
The SameSite cookie attribute is now the primary browser-level defense. SameSite=Strict prevents the cookie from being sent with any cross-site request. SameSite=Lax (the default in modern browsers) allows cookies on top-level navigations (clicking a link) but blocks them on cross-site form submissions and fetch requests. This dramatically reduces the CSRF attack surface without requiring CSRF tokens. However, CSRF tokens remain a best practice as defense-in-depth, since SameSite behavior can vary across older browsers.