CSRF: Cross-Site Request Forgery

Difficulty: Intermediate

Question

What is Cross-Site Request Forgery (CSRF), why does it work, and how do you prevent it?

Answer

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.

How the attack works

  1. The user logs into bank.example and has a session cookie.
  2. They visit evil.example, which contains an auto-submitting form with action="https://bank.example/transfer" and hidden fields for amount and payee.
  3. The browser sends the POST with the bank's session cookie attached.
  4. The bank processes the transfer because the session looks valid.

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.

Defences, in order of importance

  • SameSite cookies: 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.
  • Anti-CSRF tokens (synchronizer token pattern): the server generates a random token tied to the session, embeds it in forms or a meta tag, and rejects any state-changing request where the submitted token does not match. An attacker on another origin cannot read it.
  • Double submit cookie: for stateless apps, set a random token in a cookie and require the same value in a header; use a signed (HMAC) variant tied to the session so a subdomain cannot plant its own cookie.
  • Origin / Referer checks: reject state-changing requests whose 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.
  • Never change state on GET. SameSite=Lax lets GET navigations through, so a GET that deletes data is still exploitable.

When you do not need classic CSRF tokens

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.

Common mistakes

  • Thinking CORS prevents CSRF. CORS controls who can read responses; a simple form POST is sent regardless.
  • Assuming XSS protection is unrelated. Any XSS on your origin can read the CSRF token and bypass the protection entirely.
  • Forgetting login CSRF: forcing a victim to log into the attacker's account so their actions are recorded there.
A CSRF attack without defences. The browser attaches the session cookie even though the request came from another site.
  1. User's browser → bank.example: Logs in, receives session cookie
  2. User's browser → evil.example: Visits attacker page
  3. evil.example → User's browser: Hidden auto-submitting form
  4. User's browser → bank.example: POST /transfer with session cookie
  5. bank.example → User's browser: Transfer done, no intent checked

Code examples

Origin check plus SameSite cookie in Express

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.

Synchronizer token in a form

<!-- 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.

Key points

  • CSRF abuses the browser's automatic cookie attachment to trigger unwanted actions.
  • The attacker cannot read responses, so CSRF targets state-changing endpoints.
  • Set SameSite explicitly; Lax still allows top-level GET navigations, so never change state on GET.
  • Anti-CSRF tokens and Origin or Sec-Fetch-Site checks add a server-side layer.
  • CORS does not stop CSRF, and XSS bypasses CSRF tokens.

Common follow-up questions

  • What is the difference between SameSite=Lax and SameSite=Strict?
  • Why does an API using Bearer tokens in headers not need CSRF tokens?
  • Can CORS protect against CSRF? Why or why not?
  • What is login CSRF?

Interview tips

  • Explain the root cause in one line: the browser attaches cookies automatically.
  • Contrast CSRF with XSS: CSRF rides on the user's session from outside; XSS runs code inside your origin.
  • Mention that Bearer-token APIs are not vulnerable to CSRF but trade that for XSS exposure.

Concepts covered

CSRF, SameSite Cookie, Synchronizer Token, Double Submit Cookie, Origin Header

More Web Security (OWASP, JWT, XSS, CSRF) questions