What is the anti-forgery token, and how does it prevent CSRF?

ASP.NET MVC Security Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

CSRF is when a malicious site tricks a logged-in user's browser into submitting a request to your app using their cookies. The anti-forgery token defends against it: the server puts a secret token in the form (and a paired cookie), and [ValidateAntiForgeryToken] rejects any POST where the two don't match — an attacker can't read the token from another origin.

CSRF is when another website causes the user's browser to POST to my app while carrying the user's auth cookie — the browser sends cookies automatically regardless of which site triggered the request. The anti-forgery token stops it: the server renders a random token into the form plus a matching cookie, and the action validates that the form token and the cookie agree. A cross-origin attacker can't read that token, so their forged request fails. In Razor the form tag helper adds it automatically and I put [ValidateAntiForgeryToken] on the action, or use [AutoValidateAntiforgeryToken] globally. It's specifically for cookie-authenticated endpoints — a JWT-in-header API doesn't need it.

  • Razor's <form> tag helper emits a hidden __RequestVerificationToken automatically; the framework also sets an anti-forgery cookie.
  • The action is guarded with [ValidateAntiForgeryToken], or globally with [AutoValidateAntiforgeryToken] which validates all unsafe verbs (POST/PUT/DELETE) but not GET.
  • For AJAX, read the token and send it in a header (RequestVerificationToken).
  • Pure token-based APIs (JWT in a header, not a cookie) aren't vulnerable to classic CSRF, so they don't need it. Cookie-authenticated endpoints do.
  • Also set cookies to SameSite=Lax/Strict as defence in depth.