Skip to main content
security

CSRF (Cross-Site Request Forgery)

CSRF tricks a user's browser into making authenticated requests to a site where the user is logged in. An attacker's page includes a form or image that submits to the target site – the browser automatically attaches the user's cookies. Prevention: anti-CSRF tokens, SameSite cookies, and checking Origin/Referer headers.

Definition

Cross-Site Request Forgery exploits the browser's automatic cookie attachment. When a user is logged into bank.com, any page on any domain can trigger a request to bank.com – and the browser sends bank.com's cookies automatically. An attacker hosts a page with <form action='https://bank.com/transfer' method='POST'><input name='to' value='attacker'><input name='amount' value='10000'></form> and auto-submits it via JavaScript. The bank sees a valid authenticated request and processes the transfer. Prevention requires the server to include something the attacker cannot know: a CSRF token (random value in a hidden form field that the server validates), SameSite=Strict cookies (browser does not send cookies on cross-origin requests), or verifying the Origin header matches the expected domain. APIs using Authorization: Bearer tokens instead of cookies are inherently immune – tokens are not automatically attached.

Examples

  • Django: {% csrf_token %} in forms + CsrfViewMiddleware validates
  • Set-Cookie: session=abc; SameSite=Strict (prevents cross-origin cookie sending)
  • Express: csurf middleware generates and validates CSRF tokens

Related Protocols

Related Terms