CSRF Attacks: How Hackers Can Hijack Your Users Accounts
A user logs into their bank, then visits a malicious site in another tab. Without knowing it, the malicious site tricks their browser into sending money. This is CSRF—Cross-Site Request Forgery. It's a simple but dangerous attack that exploits how browsers send authentication cookies with every request.
How CSRF Attacks Work
Your browser sends cookies to websites you're logged into. An attacker exploits this with a hidden form on their site that sends a request to the bank:
When you visit this page while logged into your bank, the form submits on its own. Your browser includes your bank authentication cookies, so the bank thinks it's a legitimate request from you. The attacker never needs your password.
CSRF only works with state-changing operations (like sending money or changing settings). Browsers don't send cookies with requests from other websites, but they still send the request. The bank processes it because the cookies look real.
Essential Defenses
CSRF Tokens
Generate a unique token for each user session. Require it with every form that changes data:
Validate the token on your server:
Why it works: The token is unique per session and never stored as a cookie. Attackers can't guess it or read it from your website.
SameSite Cookies
Control when the browser sends authentication cookies. Combine with httpOnly for full protection:
What each flag does:
SameSite=Lax- Prevents the browser from sending cookies in cross-site POST requests (blocks CSRF)HttpOnly- Prevents JavaScript from reading the cookie (blocks XSS attacks)Secure- Only send over HTTPS connections
SameSite protects against CSRF, but older browsers don't support it. Some APIs also bypass SameSite by using Authorization headers instead of cookies. Always use CSRF tokens as a secondary defense.
Origin Validation
Verify that requests come from your own domain:
Why You Need Both Tokens and Cookies
SameSite cookies alone aren't enough. Here's why:
Defense layers:
- SameSite cookies block automatic cookie transmission (CSRF prevention)
- httpOnly prevents JavaScript theft (XSS prevention)
- CSRF tokens validate that the request is legitimate (secondary CSRF defense)
- Origin validation confirms the request source
Use all three together for complete protection.
Quick Defense Checklist
- ✅ Use CSRF tokens on all forms that change data
- ✅ Set
SameSite=Laxon authentication cookies - ✅ Validate the origin of requests
- ✅ Never use GET requests for state-changing operations
- ✅ Use HTTPS only
- ✅ Regenerate tokens after user login
Real Impact
CSRF has affected major websites: Twitter (2010), YouTube (2008), and banking platforms. Modern frameworks include built-in CSRF protection—use it.
Bottom Line
CSRF attacks are simple to execute but easy to prevent. Use defense in depth: CSRF tokens + SameSite cookies + origin validation. Your users depend on it.