In ASP.NET Core Razor Pages, what protects a charity's donation form from forged cross-site posts, and what is checked when it is submitted?
answer
- two halves that must pair
- cookie .AspNetCore.Antiforgery.<hash>
- hidden field __RequestVerificationToken
- AutoValidateAntiforgeryToken on every page
- failure: 400 Bad Request
basics
~20 sRazor Pages validates antiforgery tokens on every unsafe request automatically: the form carries a request token in __RequestVerificationToken, the browser returns a cookie token, and IAntiforgery checks that they pair and match the user. A failure returns 400.
solid answer
~40 s`AddRazorPages()` registers the antiforgery services for you, and Razor Pages adds an `[AutoValidateAntiforgeryToken]` filter to every page, so any request other than GET, HEAD, OPTIONS or TRACE is validated before the handler runs. When the donation page renders its `<form method="post">`, ASP.NET Core issues two tokens: a **cookie token** in a cookie named `.AspNetCore.Antiforgery.<hash>` (HttpOnly, SameSite=Strict) and a **request token** in the hidden `__RequestVerificationToken` field. On submit, `IAntiforgery.ValidateRequestAsync` reads the cookie and the request token (from the `RequestVerificationToken` header or the form field), decrypts both with Data Protection, and checks that they share one security token and that the request token was issued to the current user. Any failure stops the handler with `400 Bad Request`; nothing is stored in session state.
code
csharp · 14 linespublic class DonateModel(IDonationService donations) : PageModel
{
[BindProperty]
public decimal Amount { get; set; }
public void OnGet() { }
public async Task<IActionResult> OnPostAsync()
{
// Reached only if the cookie token and __RequestVerificationToken pair up.
await donations.RecordAsync(Amount);
return RedirectToPage("/Thanks");
}
}go deeper
Recall the pair: a cookie token and a hidden __RequestVerificationToken field, checked automatically on Razor Pages posts, with 400 on failure.
Explain how AddRazorPages registers the services, how the page model gets AutoValidateAntiforgeryToken, which methods it skips, and how the request token binds to the user.
Know when a page must opt out with [IgnoreAntiforgeryToken], what replaces the token there, and how cookie, header and caching options affect behaviour behind proxies and CDNs.
Weigh relying on framework-issued tokens across many apps against a shared cookie name, key ring and policy, and decide who owns exemptions such as provider callbacks.
## The two tokens ASP.NET Core issues ASP.NET Core's antiforgery system (`Microsoft.AspNetCore.Antiforgery`) protects form posts with a **token pair**. Neither half is useful alone: - The **cookie token** travels in a cookie whose name starts with `.AspNetCore.Antiforgery.` followed by a short hash of the app's Data Protection discriminator. By default the cookie is `HttpOnly`, `SameSite=Strict`, marked essential, and has no expiry, so it is a browser-session cookie. - The **request token** is written into the page, as a hidden `<input name="__RequestVerificationToken">` in the form. A script can send it in a `RequestVerificationToken` header instead. - Both are produced by the singleton `IAntiforgery` service and encrypted with **Data Protection**, so they cannot be read or forged without the app's keys. The request token embeds the same random security token as the cookie token, plus the identity of the signed-in user (a claims-based id or the user name). That binding is why a token rendered for one user does not validate for another. ## Where Razor Pages switches validation on You write no attribute for a donation page: 1. `builder.Services.AddRazorPages()` calls `AddAntiforgery()` internally, registering `IAntiforgery` and its options. 2. When Razor Pages builds each page's model, it adds an **`[AutoValidateAntiforgeryToken]`** filter unless the page already carries an antiforgery policy such as `[IgnoreAntiforgeryToken]`. 3. The form tag helper adds the hidden field to the post forms it renders (how it decides is the tag helpers' business). `AutoValidateAntiforgeryToken` skips **GET, HEAD, OPTIONS and TRACE** and validates every other method, so `OnPost`, `OnPostRefundAsync` and the rest are all covered. ## What the check does on submit `IAntiforgery.ValidateRequestAsync(HttpContext)` runs in an authorization filter before the handler: 1. Read the cookie token from the antiforgery cookie. 2. Read the request token from the header named by `AntiforgeryOptions.HeaderName` (default `RequestVerificationToken`); if there is none and the body is a form, read the `__RequestVerificationToken` field. 3. Decrypt both tokens. 4. Confirm the cookie token and request token carry the same security token, and that the request token's user matches `HttpContext.User`. If any step fails, an `AntiforgeryValidationException` is caught and the filter sets an `AntiforgeryValidationFailedResult`, which is a **`400 Bad Request`**. The handler never runs. | Failure | Message the system records | |---|---| | no cookie | The required antiforgery cookie "..." is not present. | | no field or header | The required antiforgery request token was not provided in either form field "__RequestVerificationToken" or header value "RequestVerificationToken". | | tokens from different pairs | The antiforgery cookie token and request token do not match. | | wrong user | The provided antiforgery token was meant for a different claims-based user than the current user. | ## Opting a page out A page that receives posts from a non-browser caller, such as a payment provider's server-to-server notification, cannot present a token. Put **`[IgnoreAntiforgeryToken]`** on its `PageModel` class; Razor Pages filters apply to the whole page, not to individual handler methods. That page then needs its own proof of origin, such as a signature check. ## What you can configure `builder.Services.AddAntiforgery(options => ...)` adjusts `AntiforgeryOptions`: - `Cookie`: a `CookieBuilder` for the name, `SecurePolicy`, `SameSite` and path. - `FormFieldName`: the hidden field name, `__RequestVerificationToken` by default. - `HeaderName`: the header read first, `RequestVerificationToken` by default; `null` means form only. - `SuppressXFrameOptionsHeader`: by default, a response that sets a new antiforgery cookie also gets `X-Frame-Options: SAMEORIGIN` unless the header is already present. Responses that issue tokens are also marked `Cache-Control: no-cache, no-store`, because a cached form would hand one visitor's token to another.
- How do you exempt one Razor Page, such as a payment provider's server-to-server callback, from ASP.NET Core's automatic antiforgery check?Put `[IgnoreAntiforgeryToken]` on that page's `PageModel` class. Razor Pages sees an existing antiforgery policy and does not add `[AutoValidateAntiforgeryToken]`. Filters apply per page, not per handler method, so give the callback its own page, and verify the caller another way, for example by checking the provider's request signature.
- Why does the hidden __RequestVerificationToken value change on every render while the ASP.NET Core antiforgery cookie stays the same?`GetAndStoreTokens` reuses a valid cookie token instead of issuing a new one, then creates a fresh request token that embeds the same security token. Each request token is encrypted again by Data Protection, so its text differs every time, yet any of them pairs with the cookie. Two open tabs therefore both submit successfully.
- Razor Pages forms are unprotected until each handler gets [ValidateAntiForgeryToken].
- A failed antiforgery check returns 403 Forbidden.
- The antiforgery cookie alone proves the post came from the site's own form.
- ASP.NET Core stores the expected antiforgery token in session state.
- Razor Pages validates antiforgery tokens on GET handlers too.