skip to content

In ASP.NET Core MVC, how do [ValidateAntiForgeryToken], [AutoValidateAntiforgeryToken] and [IgnoreAntiforgeryToken] differ, and which would you register globally?

level: middleimportance: must knowfreq 58%

answer

  1. three filters, one policy
  2. Validate checks GET too
  3. Auto skips GET, HEAD, OPTIONS, TRACE
  4. closest attribute wins
  5. MvcOptions.Filters for the global one

basics

~10 s

[ValidateAntiForgeryToken] validates every request, GET included; [AutoValidateAntiforgeryToken] skips GET, HEAD, OPTIONS and TRACE; [IgnoreAntiforgeryToken] turns validation off. The one closest to the action wins, so register AutoValidateAntiforgeryToken globally.

solid answer

~40 s

All three are MVC filters that implement `IAntiforgeryPolicy`, and only the **most effective** one runs: with equal `Order` (all default to 1000) an action attribute beats a controller attribute, which beats a global filter. `[ValidateAntiForgeryToken]` calls `IAntiforgery.ValidateRequestAsync` for **every** method, so on a GET action a plain link fails with 400. `[AutoValidateAntiforgeryToken]` skips GET, HEAD, OPTIONS and TRACE and validates the rest, which suits a whole app. `[IgnoreAntiforgeryToken]` switches validation off for a controller or action. So register `AutoValidateAntiforgeryToken` once in `MvcOptions.Filters` and use `[IgnoreAntiforgeryToken]` for the rare exemption. The services come from `AddControllersWithViews()`, `AddRazorPages()` or `AddMvc()`; `AddControllers()` alone does not register them.

code

csharp · 13 lines
csharp
builder.Services.AddControllersWithViews(options =>
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));

public class PledgesController : Controller
{
    [HttpPost]
    public IActionResult Create(PledgeForm form) => RedirectToAction(nameof(Thanks)); // validated (global)

    [HttpPost, IgnoreAntiforgeryToken]
    public IActionResult ProviderCallback() => Ok();                         // not validated

    public IActionResult Thanks() => View();                                   // GET: skipped
}

go deeper

for a junior

Recall the three attributes and that Razor Pages validates automatically while MVC controllers need an attribute or a global filter.

for a middle

Explain why ValidateAntiForgeryToken breaks GET links, how the most effective IAntiforgeryPolicy is chosen by order and scope, and which registration calls supply the services.

for a senior

Register AutoValidateAntiforgeryToken globally, keep exemptions explicit and reviewed, and spot controller-based forms that slipped through without a filter.

for a principal

Set the convention for a portfolio of MVC apps: global automatic validation by default, a documented exemption process, and tests that fail when a form endpoint loses its check.

## Three filters behind one policy In MVC, antiforgery is enforced by **authorization filters**, not by middleware. The three attributes in `Microsoft.AspNetCore.Mvc` are filter factories or filters that implement the marker interface `IAntiforgeryPolicy`: | Attribute | Validates | Typical use | |---|---|---| | `[ValidateAntiForgeryToken]` | every HTTP method, GET included | one action that must always be checked | | `[AutoValidateAntiforgeryToken]` | every method except GET, HEAD, OPTIONS, TRACE | the whole app, registered globally | | `[IgnoreAntiforgeryToken]` | nothing | an exempt controller or action | `[ValidateAntiForgeryToken]` resolves `ValidateAntiforgeryTokenAuthorizationFilter`, whose `ShouldValidate` always returns `true`. `[AutoValidateAntiforgeryToken]` resolves a subclass whose `ShouldValidate` returns `false` for the four safe methods. Both call `IAntiforgery.ValidateRequestAsync` and turn an `AntiforgeryValidationException` into `AntiforgeryValidationFailedResult`, a **400 Bad Request**. ## Why `[ValidateAntiForgeryToken]` on a GET breaks links `ValidateRequestAsync` itself does not skip safe methods. A GET action marked `[ValidateAntiForgeryToken]` therefore demands a cookie token and a request token; a link or a bookmark carries no request token, so the action answers 400. That is why the automatic variant exists. ## Which attribute wins Only one antiforgery policy runs per action. Each filter checks whether it is the **most effective** `IAntiforgeryPolicy` in the action's filter list and returns early if not. The list is sorted by `Order`, then by scope: 1. All three attributes default to `Order = 1000`, chosen so they run after filters that authenticate or redirect. 2. With equal `Order`, global filters come first, then controller attributes, then action attributes. 3. The **last** policy in the list, the one closest to the action, is the effective one. So a global `AutoValidateAntiforgeryToken` plus `[IgnoreAntiforgeryToken]` on one action leaves that action unchecked, and `[ValidateAntiForgeryToken]` on an action inside an ignored controller turns checking back on for that action. ## Registering it globally ```csharp builder.Services.AddControllersWithViews(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())); ``` - Every form-posting action is then covered, including ones a teammate forgets to annotate. - GET actions stay reachable from links. - Exemptions are explicit `[IgnoreAntiforgeryToken]` attributes that show up in review. ## Where the services come from - `AddControllersWithViews()`, `AddRazorPages()` and `AddMvc()` add the view services, which call `AddAntiforgery()` and register both filter types. - `AddControllers()` alone registers neither. Antiforgery protects cookie-authenticated forms, and a controllers-only JSON API usually has none. - `app.UseAntiforgery()` is not needed for these attributes: the filters validate by themselves. The middleware matters to endpoints that carry `IAntiforgeryMetadata`, such as Minimal API form handlers, or MVC actions marked `[RequireAntiforgeryToken]`. One combination is rejected outright: `[ValidateAntiForgeryToken]` and `[RequireAntiforgeryToken]` on the same controller or action make MVC throw `InvalidOperationException` ("Cannot apply [ValidateAntiForgeryTokenAttribute] and [RequireAntiforgeryTokenAttribute] at the same time"). ## Razor Pages is different Razor Pages adds `[AutoValidateAntiforgeryToken]` to every page by itself; controllers get nothing until you add an attribute or the global filter. That asymmetry is the most common reason a controller-based form is found unprotected in review. ## What reviewers look for - **`[ValidateAntiForgeryToken]` on a GET action**, usually copied from a POST action above it; the page then fails for every visitor who follows a link. - **A form-posting action with no antiforgery attribute** in an app that never registered the global filter. Nothing warns about it; the form simply accepts forged posts. - **`[IgnoreAntiforgeryToken]` on a whole controller** to exempt one callback action. Every other action in that controller loses its check; put the attribute on the one action instead. - **A global `ValidateAntiForgeryTokenAttribute`** instead of the automatic one, which breaks every GET. - **An AJAX call to a protected action without the token header**; the action is correct, the client is not, and the symptom is a 400 that only appears for script-driven requests. Each of these is visible from the attributes alone, which is one more reason to keep the policy global and the exceptions explicit.

  • With a global AutoValidateAntiforgeryToken filter in ASP.NET Core MVC, how does [IgnoreAntiforgeryToken] on one action take effect?
    Both are `IAntiforgeryPolicy` filters with `Order = 1000`. MVC sorts filters by order and then scope, so the action-level attribute lands last. Each antiforgery filter runs only if it is the most effective policy, the last one in the list, so the global filter steps aside and the action is not validated.
  • Does an ASP.NET Core MVC app need app.UseAntiforgery() for [AutoValidateAntiforgeryToken] to work?
    No. The MVC antiforgery attributes are authorization filters that call `IAntiforgery.ValidateRequestAsync` themselves. `UseAntiforgery()` serves endpoints carrying `IAntiforgeryMetadata`, such as Minimal API form handlers, Blazor forms, or MVC actions marked `[RequireAntiforgeryToken]`; it adds nothing to the attribute-based filters.

  • [AutoValidateAntiforgeryToken] validates GET requests as well.
  • [ValidateAntiForgeryToken] skips GET and HEAD the same way the automatic variant does.
  • A global antiforgery filter always overrides [IgnoreAntiforgeryToken] on an action.
  • MVC's antiforgery attributes do nothing unless app.UseAntiforgery() is in the pipeline.
  • AddControllers() registers the antiforgery services that the MVC attributes need.