SameSite Cookie
Problem
Browsers send authentication cookies with every request to a domain, even when the request originates from a malicious third-party site. This enables CSRF attacks where attackers trick users into performing authenticated actions without their knowledge or consent.
Solution
Set the SameSite cookie attribute to control when cookies are sent with cross-origin requests. This mitigates CSRF attacks by preventing cookies from being included in requests from other sites.
Example
This demonstrates how to configure the SameSite cookie attribute to prevent cross-site request forgery attacks by controlling when cookies are sent with cross-origin requests.
// Set cookie with SameSite attribute (client-side)
// Strict: Cookie only sent with same-site requests
// Secure: Only sent over HTTPS
// HttpOnly: Not accessible via JavaScript
document.cookie = "sessionId=abc123; SameSite=Strict; Secure; HttpOnly";
// Express.js server-side configuration
res.cookie('sessionId', 'abc123', {
sameSite: 'strict', // Prevents CSRF by blocking cross-site cookie sending
secure: true, // Only send cookie over HTTPS
httpOnly: true // Prevent JavaScript access to mitigate XSS
});
Benefits
- Mitigates
CSRFattacks by controlling when cookies are sent. - Provides browser-level protection without requiring
CSRFtokens. - Easy to implement with a single cookie attribute.
- Works automatically across all requests without application changes.
Tradeoffs
- Strict mode can break legitimate cross-site functionality.
- Lax mode still allows some cross-site cookie sending.
- Requires HTTPS in production (Secure attribute) to work properly.
- May need different settings for different use cases.