CSRF & SameSite
Vibe Prompt
"Explore csrf & samesite with examples and prevention techniques."
Key Concepts
- Core principles and attack vectors
- Detection and exploitation techniques
- Prevention and mitigation strategies
- Real-world examples and case studies
Practice Exercise
๐ก Practice: Ask AI to help you create a vulnerable app and test these protections.
Chapter Summary
- Understand core concepts and principles
- Master implementation methods and techniques
- Familiar with common issues and solutions
- Able to apply in real projects
Further Reading
- Official documentation and API references
- Open source examples on GitHub
- Technical books and online courses
- Community discussions and tech blogs
Implementation Example
Basic Example
# This section provides a complete implementation example
Steps
- Setup: Configure development environment
- Data: Prepare required data
- Implementation: Build core functionality
- Testing: Verify correctness
- Optimization: Improve performance
Common Errors
| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |
Code Example
import sys
def main():
print("Hello, World!")
if __name__ == "__main__":
main()
References
- Official documentation
- API reference
- Open source examples
- Community discussions
Key Points
- Understand the core concepts thoroughly
- Practice with hands-on code examples
- Apply knowledge to real-world problems
- Review and reinforce through exercises
Further Learning
- Official documentation
- Open source projects on GitHub
- Community forums and discussions
- Related courses and tutorials
What Is CSRF?
Cross-Site Request Forgery (CSRF) tricks an authenticated user into executing unwanted actions on a web application where they are logged in.
How CSRF Works
1. User logs into bank.com (gets session cookie)
2. User visits evil.com (another tab)
3. evil.com contains: <img src="https://bank.com/transfer?amount=1000&to=attacker">
4. Browser automatically sends the cookie along with the request
5. Bank processes the transfer โ thinks it's from the legitimate user!
Why Browser Sends Cookies
| Cookie Attribute | Sent Cross-Site? | |-----------------|------------------| | Default (no SameSite) | โ Yes | | SameSite=Lax | โ Yes (top-level GET) | | SameSite=Strict | โ No | | SameSite=None + Secure | โ Yes (HTTPS only) |
CSRF Prevention Strategies
1. SameSite Cookies (Modern Solution)
// Next.js: Set SameSite cookie attribute
// In API response:
res.setHeader('Set-Cookie', [
`session=${token}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=86400`
]);
| SameSite Value | Protection | UX Impact | |----------------|------------|-----------| | Strict | Maximum | Breaks links from external sites | | Lax | Good for most | Allows top-level GET navigations | | None | None | Requires Secure + explicit CSRF token |
2. CSRF Tokens (Traditional Solution)
// Server generates and validates CSRF token
import { randomBytes } from 'crypto';
// Generate token
function generateCsrfToken(): string {
return randomBytes(32).toString('hex');
}
// Store in session (not accessible via JS)
// Return in response or embed in form
// Client: Send token with state-changing requests
async function submitForm(formData: FormData) {
const response = await fetch('/api/transfer', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': getCsrfToken(), // From meta tag or cookie
},
body: JSON.stringify({ amount: 100, to: 'alice' }),
});
}
// Server: Validate token
app.post('/api/transfer', (req, res) => {
const token = req.headers['x-csrf-token'];
if (!token || token !== req.session.csrfToken) {
return res.status(403).json({ error: 'Invalid CSRF token' });
}
// Process transfer...
});
3. Custom Request Headers
// APIs protected by custom headers (not sent cross-origin)
fetch('/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Requested-By': 'my-app', // Custom header
},
});
// Server: verify custom header exists
app.post('/api/data', (req, res) => {
if (!req.headers['x-requested-by']) {
return res.status(403).json({ error: 'CSRF check failed' });
}
});
4. Origin / Referer Header Check
app.post('/api/transfer', (req, res) => {
const origin = req.headers['origin'];
const referer = req.headers['referer'];
const allowedOrigins = ['https://bank.com'];
if ((origin && !allowedOrigins.includes(origin)) ||
(referer && !allowedOrigins.includes(new URL(referer).origin))) {
return res.status(403).json({ error: 'Invalid origin' });
}
});
CSRF Prevention Comparison
| Method | Effort | Protection Level | Breaks Links? | |--------|--------|-----------------|---------------| | SameSite=Lax | Low | Good | โ No | | SameSite=Strict | Low | Maximum | โ Yes | | CSRF Token | Medium | Maximum | โ No | | Custom Header | Medium | Good | โ No | | Origin Check | Low | Moderate | โ No |
Summary
CSRF tricks authenticated users into performing unwanted actions. Prevention combines SameSite cookies, CSRF tokens, custom headers, and origin validation.
Key takeaways: | CSRF: attacker uses the victim's session cookie to make unauthorized requests | | SameSite=Lax: prevents most CSRF without breaking user experience | | SameSite=Strict: maximum protection but breaks external links | | CSRF token: secret token validated on every state-changing request | | Custom header (X-Requested-By): not sent cross-origin by browsers | | Origin/Referer check: verify the request came from your domain | | Use SameSite as baseline + CSRF tokens for sensitive actions (transfers) |
What's Next: Secure API
The next chapter covers building a fully secured API.