A CSRF attack forces an authenticated user to perform an unwanted action. The browser automatically attaches cookies, and the attacker exploits this.
How CSRF Works¶
A user is logged into bank.com. They visit evil.com with a hidden form that sends a POST to bank.com/transfer. The browser attaches the session cookie.
Defense: CSRF Token + SameSite¶
CSRF Protection — Cross-Site Request Forgery¶
Express.js¶
const csrf = require(‘csurf’); app.use(csrf({ cookie: true }));
SameSite Cookie¶
Set-Cookie: session=abc; SameSite=Lax; Secure; HttpOnly
Modern Approach¶
- SameSite=Lax is the default in modern browsers
- CSRF token for state-changing operations
- API with Bearer token in the Authorization header is immune to CSRF
Key Takeaway¶
SameSite=Lax + CSRF tokens for forms. API with Bearer token is immune to CSRF.
securitycsrfweb