TL;DR
CSRF (Cross-Site Request Forgery) tricks your browser into making requests you didn't intend. If you're logged into your bank and visit a malicious site, that site could trigger a transfer from your account. Your browser automatically includes your cookies, so the bank thinks you made the request. Prevent CSRF with tokens, SameSite cookies, and checking the Origin header.
The Simple Explanation
Imagine you're logged into your bank. Then you visit a different website with this hidden image:
Your browser loads the image by making that request. Since you're logged into the bank, your session cookie goes along with it. The bank sees a valid request from an authenticated user and processes the transfer.
You never clicked anything. You just visited a webpage. That's CSRF.
How CSRF Works
- Victim logs into vulnerable-site.com
- Victim visits attacker's page (or any site with malicious content)
- Attacker's page triggers a request to vulnerable-site.com
- Browser automatically includes cookies for vulnerable-site.com
- vulnerable-site.com thinks it's a legitimate request from the victim
Preventing CSRF
1. CSRF Tokens
Include a secret token in forms that the server validates. Attackers can't guess this token.
2. SameSite Cookies
Modern browsers support SameSite cookie attributes that restrict when cookies are sent:
Set-Cookie: session=abc123; SameSite=Strict; Secure; HttpOnly
3. Check Origin/Referer Headers
Verify that requests come from your own domain.
When CSRF Doesn't Apply
CSRF is mainly a concern when authentication uses cookies (automatically sent by browser). If your API uses Authorization headers with tokens (like Bearer tokens), CSRF is less of a concern because browsers don't automatically send Authorization headers.
What is the difference between CSRF and XSS?
XSS injects malicious scripts that run in users' browsers. CSRF tricks the browser into making requests the user didn't intend. XSS exploits trust a user has in a website. CSRF exploits trust a website has in a user's browser.
Do I need CSRF protection for APIs?
If your API uses cookies for authentication, yes. If it uses Authorization headers with tokens (like Bearer tokens), CSRF is less of a concern because browsers don't automatically send Authorization headers. Modern SPAs using JWT in headers are naturally CSRF-resistant.
What is the SameSite cookie attribute?
SameSite controls whether cookies are sent with cross-site requests. SameSite=Strict only sends cookies for same-site requests. SameSite=Lax sends cookies for navigation but not for embedded content. SameSite=None sends cookies everywhere but requires Secure. Modern browsers default to Lax, providing basic CSRF protection.