skip to content

Donation posts on an ASP.NET Core Razor Pages site intermittently return 400 Bad Request; how do you find which antiforgery check failed, and what does each failure point to?

level: seniorimportance: should knowfreq 34%

answer

  1. the 400 hides its reason
  2. log category ...Mvc.ViewFeatures.Filters
  3. cookie missing vs token missing
  4. different claims-based user
  5. could not be decrypted: key ring

basics

~10 s

Raise logging for Microsoft.AspNetCore.Mvc.ViewFeatures.Filters to Information and read the 'Antiforgery token validation failed' message. A missing cookie, missing request token, user mismatch and decryption failure each point to a different cause.

solid answer

~40 s

The 400 comes from `AntiforgeryValidationFailedResult`; the reason is only in the log. The Razor Pages filter logs "Antiforgery token validation failed. {Message}" at **Information** under `Microsoft.AspNetCore.Mvc.ViewFeatures.Filters`, which the template's `"Microsoft.AspNetCore": "Warning"` hides. The message maps to a cause: **cookie not present** means the browser did not send the `SameSite=Strict` session cookie, as with a cross-site POST back from a payment page or an expired browser session; **request token not provided** means a form without the hidden field or a script without the header; **meant for a different claims-based user** means the form was rendered before sign-in or sign-out; **could not be decrypted** means the Data Protection keys differ between instances or were lost; **cookie token and request token do not match** means the two came from different issues.

code

json · 9 lines
json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.AspNetCore.Mvc.ViewFeatures.Filters": "Information"
    }
  }
}

go deeper

for a junior

Know that an antiforgery failure is a 400 with no explanation in the response, and that the reason is in the server log.

for a middle

Map each validation message to its cause: missing cookie, missing token, different user, decryption failure, mismatched pair.

for a senior

Diagnose from logs in production, separate key-ring problems after a scale-out from stale pages and third-party returns, and fix each with the narrowest change.

for a principal

Decide what antiforgery telemetry every web app keeps, and who owns exemptions for third-party callbacks across teams so they do not spread.

## Why the response tells you nothing When validation fails in Razor Pages or MVC, the antiforgery filter catches `AntiforgeryValidationException` and sets **`AntiforgeryValidationFailedResult`**, a plain `400 Bad Request` with no body that names the reason. The reason is in two places only: - the exception message, which the filter logs as "Antiforgery token validation failed. {Message}" at **Information**, under the `Microsoft.AspNetCore.Mvc.ViewFeatures.Filters` category; - for undecryptable cookies only, an **Error** entry, "An exception was thrown while deserializing the token.", written when a page is rendered and the system replaces the unreadable cookie with a new one. The web templates set `"Microsoft.AspNetCore": "Warning"` in `appsettings.json`, which hides the filter's Information message. Raise that one category while you diagnose. ## Mapping each message to a cause | Message (abridged) | What it points to | |---|---| | The required antiforgery cookie "..." is not present. | the browser did not send the cookie | | The required antiforgery request token was not provided in either form field "__RequestVerificationToken" or header value "RequestVerificationToken". | no hidden field and no header | | The provided antiforgery token was meant for a different claims-based user than the current user. | the form predates a sign-in or sign-out | | The antiforgery token could not be decrypted. | the keys that encrypted it are not available here | | The antiforgery cookie token and request token do not match. | the two tokens came from different issues | ## Working through the common causes 1. **Cookie not present.** The antiforgery cookie defaults to `SameSite=Strict` and has no expiry, so it is a browser-session cookie. A payment provider that sends the donor back with a cross-site **POST** to `/Donate/Thanks` arrives without it, and so does a form left open after the browser was restarted. A cookie path set from `PathBase` can also keep it off requests to another base path. For a provider callback, move the handler to its own page with `[IgnoreAntiforgeryToken]` and verify the provider's signature instead. 2. **Request token not provided.** A form written as raw HTML without the form tag helper has no hidden field, or a script posts without the header. Check the posted body or headers in the browser's network panel, and compare the header name with `AntiforgeryOptions.HeaderName`. 3. **Different user.** The donor opened the form, signed in from another tab, and then submitted. The request token was issued to the anonymous user and is now refused. Redirect after sign-in so pages re-render with fresh tokens, and have scripts fetch a new token after login. 4. **Could not be decrypted.** The token was encrypted by another instance whose key ring this instance does not share, or the keys were lost when a container restarted. This is an operations problem, fixed in the Data Protection configuration, not in the form; donors who reload the page get new tokens and succeed. 5. **Tokens do not match.** The request token was issued with a different cookie: the donor cleared cookies, or the cookie was replaced, while an old page stayed open; or a cache served another visitor's page with its request token. Token responses are marked `Cache-Control: no-cache, no-store` for this reason, so look for a proxy or output cache that ignores that. ## Making it observable - Keep `Microsoft.AspNetCore.Mvc.ViewFeatures.Filters` at Information in production if antiforgery failures matter to you; the volume is low. - Count 400s on form-posting pages separately from validation 400s, so a key-ring problem after a deployment shows up as a spike. - Do not respond to intermittent failures by disabling antiforgery: each message above has a specific fix, and an exemption should be as narrow as one page. ## What not to conclude - A 400 here is rarely an attack; most are stale pages, cross-site returns from third parties, or deployment problems. - "Could not be decrypted" can mean tampering, but after a scale-out or redeploy it far more often means the keys differ.

  • Why does an ASP.NET Core antiforgery failure say 'could not be decrypted' after the site moved from one instance to two?
    Both tokens are protected with Data Protection. If each instance has its own key ring, a token issued by instance A cannot be decrypted by instance B, so any request that lands on the other instance fails. The fix is a shared, persisted key ring with one application name, which is Data Protection configuration rather than antiforgery code.
  • A payment provider POSTs donors back to an ASP.NET Core Razor Page and every return gets 400. Why?
    The antiforgery cookie is `SameSite=Strict`, so the browser omits it on a POST that starts on another site, and the provider's form has no request token anyway. Put the return handler on its own page with `[IgnoreAntiforgeryToken]` and validate the provider's signature, or ask the provider to return with a GET redirect.

A cloakroom ticket stub and its matching coat tag: the attendant refuses the coat if you lost the stub, brought a stub from another evening, or the stub was issued to someone else, and each refusal needs a different fix.

  • Every antiforgery 400 means a CSRF attack was blocked.
  • 'The antiforgery token could not be decrypted' always means the user tampered with the form.
  • Disabling antiforgery globally is a reasonable fix for intermittent 400s.
  • The antiforgery cookie is persistent, so restarting the browser cannot affect it.
  • The 400 response body tells the client which antiforgery check failed.