Nodea — logo

CSRF (Cross-Site Request Forgery)

CSRF (Cross-Site Request Forgery, sometimes pronounced "sea-surf") is a web attack in which a malicious site causes a victim's browser to send an unwanted request to another site where the victim is currently authenticated. Because browsers attach session cookies to requests automatically, the target server sees valid credentials and executes the action — changing an email address, resetting a password, creating an admin account or moving money — as if the user had asked for it.

How a CSRF attack works

The victim logs into a banking site or admin panel and, in another tab, visits a page controlled by the attacker. That page contains a hidden form auto-submitted by JavaScript, or something as trivial as an image tag pointing at a state-changing URL. When the browser fires the request, it dutifully includes the victim's session cookie. Without dedicated defenses, the server cannot distinguish this forged request from a legitimate one. Crucially, the attacker never steals a password or session — the attack weaponizes the server's trust in an authenticated browser. This is what separates CSRF from XSS, which injects and executes script inside the trusted site itself.

Defenses

  • CSRF tokens — the server embeds an unpredictable, session-bound token in every form or exposes it for AJAX requests, and rejects submissions without a valid one. Every major framework ships this: Laravel's @csrf directive and verification middleware, Django, Rails, Spring Security.
  • SameSite cookiesLax (the modern default) or Strict stops cookies from riding along on most cross-site requests; treat it as defense in depth, not a sole control.
  • Origin/Referer validation — reject state-changing requests arriving from foreign origins.
  • Re-authentication or two-factor confirmation for critical operations like transfers and password changes.
  • Correct HTTP semantics — never mutate state on GET; forgeable navigation requests then become harmless.

Practical applications

For most teams, CSRF protection today means not disabling what the framework provides. Vulnerabilities creep in around hand-rolled AJAX endpoints, cookie-authenticated APIs, webhook receivers and legacy code "simplified" by removing token checks. Include CSRF cases in security reviews alongside XSS and SQL injection tests — and remember that a single XSS hole can read tokens and defeat CSRF defenses entirely, so the protections stand or fall together.

Powiązane pojęcia

Najczęstsze pytania

Are APIs using bearer tokens vulnerable to CSRF?

Generally no. CSRF depends on credentials the browser attaches automatically, which means cookies (and HTTP Basic auth). An API authenticated with an Authorization header set explicitly by JavaScript cannot be forged from another origin, because the attacker's page has no way to add that header cross-site.