Difficulty: Intermediate
What is Cross-Site Request Forgery (CSRF), why does it work, and how do you prevent it?
Cross-Site Request Forgery (CSRF) tricks a logged-in user's browser into sending a state-changing request to your site from a page the attacker controls. It works because browsers automatically attach cookies to requests for your domain, so the server sees a valid session and cannot tell the user did not intend the action. You prevent it with SameSite cookies, anti-CSRF tokens and checking the Origin header on state-changing requests.
bank.example and has a session cookie.evil.example, which contains an auto-submitting form with action="https://bank.example/transfer" and hidden fields for amount and payee.The attacker never sees the response; CSRF is about causing an action, not reading data. That is why it targets state-changing endpoints: changing email, transferring money, updating UPI settings, deleting accounts.
SameSite=Lax stops cookies on cross-site POSTs, iframes and fetches but still sends them on top-level GET navigations. SameSite=Strict never sends them cross-site. Chromium treats cookies without a SameSite attribute as Lax, but Firefox and Safari do not apply that default the same way, so set it explicitly.Origin header is not on your allowlist. Modern browsers also send Sec-Fetch-Site, which tells you if a request is same-origin or cross-site.SameSite=Lax lets GET navigations through, so a GET that deletes data is still exploitable.If your API authenticates with an Authorization: Bearer header set by JavaScript, browsers do not attach it automatically, so CSRF does not apply. The trade-off is that tokens accessible to JS are exposed to XSS. Also, a JSON API that only accepts Content-Type: application/json forces a CORS preflight for cross-origin requests, which raises the bar, but do not rely on this alone.
const ALLOWED = new Set(['https://app.example.in']);
// Session cookie that is not sent on cross-site POSTs
res.cookie('sid', sessionId, {
httpOnly: true,
secure: true,
sameSite: 'lax',
});
// Reject cross-site state-changing requests
app.use((req, res, next) => {
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
const site = req.get('Sec-Fetch-Site');
const origin = req.get('Origin');
if (site === 'same-origin' || (origin && ALLOWED.has(origin))) {
return next();
}
res.status(403).send('CSRF check failed');
});
SameSite handles most cases in the browser, and the server-side origin check is a second layer that does not rely on cookie defaults.
<!-- Server renders a per-session random token -->
<form method="POST" action="/account/email">
<input type="hidden" name="_csrf" value="b7f3c9e1a4..." />
<input type="email" name="email" />
<button>Update email</button>
</form>
<!-- Server compares _csrf with the value stored in the session -->
An attacker's page cannot read this token because of the Same-Origin Policy, so it cannot forge a valid request.
CSRF, SameSite Cookie, Synchronizer Token, Double Submit Cookie, Origin Header