liveBook · Manning

ValidateAntiForgeryToken attribute

As explained in ASP.NET Core in Action, 3e

The ValidateAntiForgeryToken attribute is an ASP.NET Core MVC attribute that requires validation of antiforgery tokens for a request.

The [ValidateAntiForgeryToken] attribute protects state-changing MVC controller actions from cross-site request forgery (CSRF). It requires matching antiforgery tokens in the request cookie and form data, rejecting requests when either token is missing or does not match. section 29.2

Use it with MVC controllers and views as follows:

  • Add [ValidateAntiForgeryToken] to every vulnerable action that changes state, such as POST or DELETE actions. section 29.2
  • Keep the form antiforgery token. ASP.NET Core adds it to forms as a hidden __RequestVerificationToken field. section 29.2
  • Do not rely on automatic validation for MVC controllers with views; unlike Razor Pages, they require explicit attributes. section 29.2

Protected state-changing form

A withdrawal form posts an amount to an MVC action marked with [ValidateAntiForgeryToken]. A legitimate browser request includes the cookie token and hidden form token; a forged form cannot read and reproduce the hidden token, so the request is rejected. section 29.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains token placement, matching, rejected requests, and dangerous verbs, but does not detail attribute configuration.
Examples
Uses a withdrawal form, a hidden request-verification field, and contrasting legitimate and malicious requests.
What it assumes
Assumes MVC forms and controller actions, while explaining CSRF, cookies, and antiforgery tokens from their practical behavior.
What you can do after
Apply the attribute to vulnerable MVC actions and recognize why requests with missing or mismatched tokens fail.
How it connects
Connects MVC controllers, Razor Pages, forms, cookies, authentication, CSRF, and IgnoreAntiforgeryToken.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.