CodePark/ questions / XSS, CSRF & browser-facing risks
START PRACTICINGPRACTICE
Backend question · Auth & security › XSS, CSRF & browser-facing risks

How do you defend a cookie-authenticated web app against CSRF?

Use several layers: SameSite cookies, CSRF tokens and an Origin check.

CSRF (cross-site request forgery) works because browsers attach cookies to requests automatically. So a malicious page can send a request that changes data, and the server accepts it as the logged-in user. CSRF only matters when the browser sends credentials automatically, as with cookies or HTTP basic auth.

Defences:

  • Set SameSite=Lax or Strict on session cookies. This stops the browser sending them on most cross-site requests.
  • Require a CSRF token on every request that changes state. In the synchronizer pattern, the server stores a random token in the session and expects it back in a header or form field. For stateless setups, use the signed double-submit cookie pattern.
  • Check the Origin header against an allowlist. Fall back to Referer if Origin is missing.
  • Never change state on GET.
  • Consider requiring a custom header on API calls.

XSS defeats all of these defences. So CSRF defences assume you have already handled XSS.

  • CSRF only matters for credentials the browser sends automatically, like cookies.
  • SameSite cookies are the baseline defence.
  • Use synchronizer tokens or signed double-submit tokens.
  • Check the Origin header, or Referer as a fallback.
  • Never change state on GET. XSS bypasses all CSRF defences.