How do you give a JavaScript front end ASP.NET Core antiforgery tokens for cookie-authenticated fetch calls, and what does AntiforgeryOptions.HeaderName change?
answer
- script cannot read the HttpOnly cookie
- GetAndStoreTokens returns AntiforgeryTokenSet
- default header RequestVerificationToken
- header read before the form body
- new token after sign-in
basics
~20 sCall IAntiforgery.GetAndStoreTokens in an endpoint, hand the returned RequestToken to the script, and have it send the value in the header named by AntiforgeryOptions.HeaderName (RequestVerificationToken by default). HeaderName renames that header; null disables header tokens.
solid answer
~40 sThe cookie token stays in its HttpOnly `.AspNetCore.Antiforgery.*` cookie, so script needs the **request token**. An endpoint calls `IAntiforgery.GetAndStoreTokens(HttpContext)`, which writes or reuses the cookie and returns an `AntiforgeryTokenSet` with `RequestToken` and `HeaderName`; return the token in JSON or in a separate script-readable cookie. The script sends it in the header named by `AntiforgeryOptions.HeaderName`: `RequestVerificationToken` by default, or a name like `X-XSRF-TOKEN` if you set it. The token store reads that header first and parses the form only when no header came and the body is form content, so large uploads are not buffered just to find a token. Validation is automatic for MVC actions with `[AutoValidateAntiforgeryToken]`; a JSON-bound Minimal API endpoint must call `ValidateRequestAsync` itself. Because the token names the user, fetch a new one after sign-in.
code
csharp · 21 linesbuilder.Services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
app.MapGet("/antiforgery/token", (IAntiforgery antiforgery, HttpContext context) =>
{
var tokens = antiforgery.GetAndStoreTokens(context);
return Results.Ok(new { token = tokens.RequestToken, header = tokens.HeaderName });
});
app.MapPost("/api/pledges", async (Pledge pledge, IAntiforgery antiforgery, HttpContext context) =>
{
try
{
await antiforgery.ValidateRequestAsync(context);
}
catch (AntiforgeryValidationException)
{
return Results.BadRequest();
}
return Results.Ok(pledge);
}).RequireAuthorization();go deeper
Know that a JavaScript client sends the antiforgery request token in a header, RequestVerificationToken by default, while the cookie is attached by the browser.
Explain GetAndStoreTokens versus GetTokens, what AntiforgeryTokenSet carries, and how HeaderName and the form fallback decide where the token is read from.
Make sure every cookie-authenticated JSON endpoint actually validates the header, refresh tokens across sign-in and sign-out, and keep token responses uncacheable.
Decide between cookie sessions with antiforgery headers and bearer tokens for browser clients, weighing XSS exposure, CSRF exposure and how many front ends share the API.
## Why a script cannot just use the cookie ASP.NET Core issues two tokens. The **cookie token** lives in the `.AspNetCore.Antiforgery.<hash>` cookie, which is `HttpOnly`, so script cannot read it, and it does not need to: the browser attaches it to same-site requests by itself. What the script must supply is the **request token**, the value a server-rendered form would put in `__RequestVerificationToken`. The check succeeds only when the request token arrives alongside a matching cookie, and only a page served by the app can obtain it. ## Handing the token to the script `IAntiforgery` offers three methods for issuing tokens: | Method | Writes the cookie? | Returns | |---|---|---| | `GetAndStoreTokens(HttpContext)` | yes, or reuses a valid one | `AntiforgeryTokenSet` | | `GetTokens(HttpContext)` | no | `AntiforgeryTokenSet` | | `SetCookieTokenAndHeader(HttpContext)` | yes | nothing | `AntiforgeryTokenSet` exposes `RequestToken`, `CookieToken`, `FormFieldName` and `HeaderName`. Two common delivery shapes: - **A JSON endpoint**, for example `GET /antiforgery/token`, that returns `tokens.RequestToken` and `tokens.HeaderName`; the script fetches it once and keeps it in memory. - **A second, script-readable cookie** (often named `XSRF-TOKEN`, with `HttpOnly = false`) written from `tokens.RequestToken`, which some front-end HTTP clients pick up and echo in an `X-XSRF-TOKEN` header automatically. When `GetAndStoreTokens` writes a new cookie it also adds `X-Frame-Options: SAMEORIGIN` (unless `SuppressXFrameOptionsHeader` is set or the header exists), and it marks the response `Cache-Control: no-cache, no-store`, so a token response is never cached and served to someone else. ## What `HeaderName` controls `AntiforgeryOptions.HeaderName` is the request header the token store reads: 1. If `HeaderName` is not `null`, read the token from that header. 2. If no header value arrived and the request has a form content type, read `FormFieldName` from the form, unless `SuppressReadingTokenFromFormBody` is `true`. 3. Pair whatever was found with the cookie token. Consequences: - The default is **`RequestVerificationToken`**. Set `HeaderName = "X-XSRF-TOKEN"` to match a client library's convention instead of rewriting the client. - Setting `HeaderName = null` makes the system accept **form fields only**. - Reading the header first means a multipart upload does not have to be buffered and parsed just to find the token. ## Making sure something validates the header Sending the header is half the job; an endpoint must check it: - **MVC controllers**: `[AutoValidateAntiforgeryToken]` (globally or per controller) validates the header on POST, PUT, PATCH and DELETE alike. - **Minimal API form endpoints**: `UseAntiforgery()` validates them, header or field. - **Minimal API JSON endpoints**: binding JSON adds no antiforgery metadata, so nothing checks them automatically. Call `await antiforgery.ValidateRequestAsync(context)` in the handler or an endpoint filter and turn `AntiforgeryValidationException` into a 400. `IsRequestValidAsync` returns a `bool` instead, and treats GET, HEAD, OPTIONS and TRACE as valid. ## Tokens are tied to the user `DefaultAntiforgeryTokenGenerator` embeds the signed-in user's claims-based id (or the user name) in the request token. A token fetched while anonymous fails after sign-in with "The provided antiforgery token was meant for a different claims-based user than the current user." A single-page app should therefore request a fresh token after login and logout, rather than caching one token for the whole session. ## A checklist for the charity's script-driven pledge widget 1. Register `AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN")` only if the client library insists on that name; otherwise keep the default. 2. Serve the request token from an endpoint the widget calls on load, and again after sign-in. 3. Send it on every state-changing call in the configured header, never in the URL. 4. Validate it on the server for every cookie-authenticated endpoint the widget calls, including JSON and DELETE endpoints that the middleware does not cover. 5. Keep the antiforgery cookie `HttpOnly`; only the request token is meant for script.
- What does setting AntiforgeryOptions.HeaderName to null do in ASP.NET Core?The token store stops looking at headers and reads the request token only from the form field named by `FormFieldName`. A script sending the token in a header then fails with "The required antiforgery form field ... is not present." Use it only when every protected request is a classic form post.
- A single-page app gets 400 from ASP.NET Core on its first POST after the user logs in. Why, and what is the fix?The request token it holds was issued while the user was anonymous, and ASP.NET Core embeds the user's identity in the token, so validation now fails with a different-user message. Call the token endpoint again after sign-in, and after sign-out, so `GetAndStoreTokens` issues a request token for the current principal.
- The default ASP.NET Core antiforgery header is X-XSRF-TOKEN.
- Set the .AspNetCore.Antiforgery cookie to HttpOnly = false so script can send it as the token.
- A token fetched before sign-in keeps validating after the user logs in.
- GetAndStoreTokens also validates the current request.
- UseAntiforgery automatically validates JSON-bound Minimal API endpoints that receive the header.