Security Hardening and Production AuthLesson 6.1
CSRF attacks and how SameSite cookies prevent them
CSRF attack mechanism, cross-site request, SameSite=Strict vs Lax vs None, Double Submit Cookie pattern, CSRF token header, Origin header validation
CSRF Attacks and SameSite Prevention
Cross-Site Request Forgery (CSRF) exploits the browser's automatic cookie sending. A malicious page can make a POST request to your API, and the browser includes the victim's session cookie automatically.
SameSite cookie attribute is the modern defense:
SameSite=Strict: Cookie never sent on any cross-site request — including navigating from an external link. Most secure, but breaks some legitimate cross-site flows.SameSite=Lax(browser default for new cookies): Cookie sent on top-level navigations (clicking a link) but not on cross-site sub-requests (fetch, iframe, img). Sufficient for most apps.SameSite=None; Secure: Cookie sent on all cross-site requests. Required for embedded widgets and third-party integrations. Must pair withSecure.
// For APIs only called from your own front end
app.use(session({
cookie: { sameSite: 'strict', httpOnly: true, secure: true }
}));
// For APIs needing extra CSRF protection (SameSite=Lax default)
app.use((req, res, next) => {
if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(req.method)) {
const origin = req.headers.origin;
if (origin && !origin.startsWith(process.env.ALLOWED_ORIGIN)) {
return res.status(403).json({ error: 'CSRF check failed' });
}
}
next();
});Bearer tokens in Authorization headers are not CSRF-vulnerable because browsers do not automatically set custom headers on cross-site requests. CSRF is a cookie-only problem.
