MintPlayer.AspNetCore.SpaServices.Xsrf
10.8.1
See the version list below for details.
dotnet add package MintPlayer.AspNetCore.SpaServices.Xsrf --version 10.8.1
NuGet\Install-Package MintPlayer.AspNetCore.SpaServices.Xsrf -Version 10.8.1
<PackageReference Include="MintPlayer.AspNetCore.SpaServices.Xsrf" Version="10.8.1" />
<PackageVersion Include="MintPlayer.AspNetCore.SpaServices.Xsrf" Version="10.8.1" />
<PackageReference Include="MintPlayer.AspNetCore.SpaServices.Xsrf" />
paket add MintPlayer.AspNetCore.SpaServices.Xsrf --version 10.8.1
#r "nuget: MintPlayer.AspNetCore.SpaServices.Xsrf, 10.8.1"
#:package MintPlayer.AspNetCore.SpaServices.Xsrf@10.8.1
#addin nuget:?package=MintPlayer.AspNetCore.SpaServices.Xsrf&version=10.8.1
#tool nuget:?package=MintPlayer.AspNetCore.SpaServices.Xsrf&version=10.8.1
MintPlayer.AspNetCore.SpaServices.Xsrf
ASP.NET Core's antiforgery system expects a server-rendered form or view to emit the request token. A single-page application has neither, so the token never reaches the browser and every [ValidateAntiForgeryToken] endpoint rejects the SPA's requests. This package closes that gap with one middleware: on every response it obtains an antiforgery token pair and writes the request token to a JavaScript-readable XSRF-TOKEN cookie — exactly the cookie Angular's HttpClient looks for — so the SPA sends it back as a header and normal antiforgery validation just works.
Installation
NuGet Package Manager
Install-Package MintPlayer.AspNetCore.SpaServices.Xsrf
.NET CLI
dotnet add package MintPlayer.AspNetCore.SpaServices.Xsrf
Getting started: a new ASP.NET Core app and a new Angular workspace
These steps go from nothing to an Angular app whose POSTs pass antiforgery validation. If you already have one half, skip its step and do the rest.
You need the .NET 10 SDK or later, Node.js 20.19+, 22.12+ or 24, and the Angular CLI (npm install -g @angular/cli).
Do you want server-side rendering too? Then follow the Prerendering getting-started guide first. After that, only steps 1, 4, 5 and 6 below apply: add the package, the antiforgery lines in Program.cs, the endpoint and the Angular configuration.
1. Create the ASP.NET Core app
dotnet new web -n MyApp
cd MyApp
dotnet add package MintPlayer.AspNetCore.SpaServices.Xsrf
dotnet add package MintPlayer.AspNetCore.SpaServices
MintPlayer.AspNetCore.SpaServices serves the Angular app (UseSpaImproved). This package doesn't depend on it, so any other way of serving the SPA works too.
2. Create the Angular workspace in ClientApp
Run this in the project folder, next to MyApp.csproj:
ng new ClientApp --ssr=false --skip-git
The SPA packages look for the SPA in ClientApp by default.
3. ClientApp/angular.json: set the output path
Add "outputPath": "dist" to projects.ClientApp.architect.build.options:
"build": {
"builder": "@angular/build:application",
"options": {
"outputPath": "dist",
"browser": "src/main.ts",
// ...
}
}
Without it Angular writes to dist/ClientApp/browser, and RootPath in step 4 would have to say so.
4. Program.cs
Replace the generated file. In particular, the template's app.MapGet("/", () => "Hello World!") would answer / before the SPA could.
using MintPlayer.AspNetCore.SpaServices.Extensions;
using MintPlayer.AspNetCore.SpaServices.Xsrf;
var builder = WebApplication.CreateBuilder(args);
// AddControllersWithViews, not AddControllers: [ValidateAntiForgeryToken]'s filter lives in the view features.
builder.Services.AddControllersWithViews();
// The header the SPA sends the request token in. Required: it has no default.
builder.Services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
builder.Services.AddSpaStaticFilesImproved(configuration =>
{
// The Angular build output (angular.json "outputPath": "dist").
configuration.RootPath = "ClientApp/dist/browser";
});
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
if (!app.Environment.IsDevelopment())
{
// Static files first: they short-circuit, so hashed bundles get no per-user cookie and stay cacheable.
app.UseSpaStaticFilesImproved();
}
// Before whatever serves index.html, so the page load that starts the app sets the XSRF-TOKEN cookie.
app.UseAntiforgeryGenerator();
app.UseRouting();
app.MapControllers();
// Explicit: endpoints must run here, before the SPA middleware, which answers every request that reaches
// it. Without this call WebApplication runs them at the very end of the pipeline, so they are never reached.
app.UseEndpoints(_ => { });
app.UseSpaImproved(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (app.Environment.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
app.Run();
5. A validated endpoint
Controllers/WeatherForecastController.cs:
using Microsoft.AspNetCore.Mvc;
namespace MyApp.Controllers;
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpPost]
[ValidateAntiForgeryToken] // rejects the request unless X-XSRF-TOKEN matches the antiforgery cookie
public IActionResult Create() => Ok(new { created = true });
}
Validate only mutating verbs: Angular doesn't send the header on GET or HEAD. To validate every POST/PUT/PATCH/DELETE without decorating each action, register [AutoValidateAntiforgeryToken] as a global filter: AddControllersWithViews(o => o.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())).
6. Angular: HttpClient with XSRF names
ClientApp/src/app/app.config.ts, add provideHttpClient to the generated providers:
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withXsrfConfiguration } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
// ...the providers ng new generated
provideRouter(routes),
provideHttpClient(withXsrfConfiguration({
cookieName: 'XSRF-TOKEN', // the cookie UseAntiforgeryGenerator writes
headerName: 'X-XSRF-TOKEN' // AntiforgeryOptions.HeaderName
}))
]
};
These are Angular's defaults, so provideHttpClient() alone also works; naming them keeps the two sides visibly in step. Then call the API with a relative URL; Angular adds the header only to relative or same-origin requests:
this.http.post('/api/WeatherForecast', {}).subscribe();
For an NgModule app, see Angular: NgModule bootstrap.
7. Run it
dotnet run
Don't start ng serve yourself: the middleware starts it. Open the app. The browser's dev tools should show an XSRF-TOKEN cookie, and the POST should carry an X-XSRF-TOKEN header and return 200. Without the header, the same request returns 400.
How it works, end to end
- You register ASP.NET Core's antiforgery services and tell them which request header carries the token:
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"). - You add this package's middleware with
app.UseAntiforgeryGenerator(). - On each request the middleware hooks
Response.OnStarting. Just before response headers are sent it callsIAntiforgery.GetAndStoreTokens(httpContext), which produces a token pair: a cookie token (written by the antiforgery system itself into its ownHttpOnlycookie) and a request token. - The middleware appends the request token to a second cookie: name
XSRF-TOKEN,Path=/,SameSite=Strict,Secureon HTTPS requests, and — importantly —HttpOnly = false, so client-side JavaScript can read it. That is the whole point: anHttpOnlycookie would be invisible to the SPA. - The SPA reads that cookie and echoes it in the configured header. Angular's
HttpClientdoes this automatically for same-origin mutating requests. - Your endpoints validate as usual with
[ValidateAntiForgeryToken],[AutoValidateAntiforgeryToken], or a global filter. Validation compares the header's request token against the antiforgery cookie token; both must be present and must match.
The middleware only issues tokens. It never validates and never rejects a request — validation stays entirely with the framework's antiforgery attributes and filters.
Public surface
| Member | Description |
|---|---|
AntiforgeryExtensions.UseAntiforgeryGenerator(this IApplicationBuilder builder) |
Adds the middleware that generates an XSRF token for the current user and stores it in a cookie named XSRF-TOKEN. |
AntiforgeryExtensions.UseAntiforgeryGenerator(this IApplicationBuilder builder, Action<XsrfOptions> configure) |
The same, with the cookie and the cache-header policy configured. |
XsrfOptions |
Cookie (a read-only CookieBuilder: name, path, SameSite, SecurePolicy, domain), CacheHeaders, and ShouldIssue. |
XsrfCacheHeaderPolicy |
PreservePrivate (default) or NoStore. See Caching. |
[SkipXsrfToken] / .SkipXsrfToken() / ISkipXsrfTokenMetadata |
Keeps a controller, action, endpoint or route group out of the mint, without taking it out of the pipeline. See Keeping an endpoint out of the mint. |
XsrfOptions.ShouldIssue |
Func<HttpContext, bool>?: the same per response, for responses with no endpoint. null (default) always issues. |
app.UseAntiforgeryGenerator(options =>
{
options.Cookie.Name = "CUSTOM-XSRF"; // configure the properties
options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // ...not the builder
});
Cookie is deliberately get-only. The hardened defaults live in its initialiser, so assigning a
fresh CookieBuilder — the obvious-looking way to rename the cookie — would silently reset
SameSite to Unspecified and hand the choice back to the browser, which is the very defect this
release fixes. Setting the properties keeps everything you did not mention.
Configurations that cannot work are rejected at startup rather than left to be diagnosed from a 400
much later: an HttpOnly cookie the SPA could not read, or SameSite=None without Secure, each
throw an ArgumentException from UseAntiforgeryGenerator.
There is no AddXsrf() or other service-registration helper — the services you need are the framework's own AddAntiforgery(). The middleware resolves IAntiforgery from DI, so AddAntiforgery() (or something that includes it, such as AddControllersWithViews()/AddMvc()/AddRazorPages()) must be registered, otherwise the pipeline throws on the first request.
Cookie and header names
| Name | Value | Configurable? |
|---|---|---|
| Request-token cookie written by this middleware | XSRF-TOKEN |
Yes — XsrfOptions.Cookie.Name, via the configuring overload. HttpOnly=false is fixed: an HttpOnly cookie would be invisible to the SPA, so setting it is rejected at startup. |
| Request header read during validation | X-XSRF-TOKEN by convention |
Yes — AntiforgeryOptions.HeaderName. It has no default; you must set it, or header-based validation won't be attempted at all. |
| Antiforgery's own cookie token cookie | .AspNetCore.Antiforgery.<hash> |
Yes — AntiforgeryOptions.Cookie. This is not the cookie the SPA reads. |
Two consequences worth internalising:
AntiforgeryOptions.Cookie.Namedoes not rename the SPA-visible cookie. It configures the framework's internal cookie-token cookie. If you setAntiforgeryOptions.Cookie.Name = "CUSTOM-XSRF-TOKEN"and then configure your SPA to readCUSTOM-XSRF-TOKEN, the SPA will read the wrong (andHttpOnly) cookie and validation will fail. To rename the cookie the SPA reads, use this package'sXsrfOptions.Cookie.Nameand the matchingcookieNamein your SPA.- The two are separate cookies with separate options.
AntiforgeryOptions.Cookieis theHttpOnlyhalf the server validates against;XsrfOptions.Cookieis the script-readable half the SPA echoes back.
Because the values happen to be Angular's defaults, an Angular app usually needs no client configuration at all.
Complete example
Program.cs (minimal hosting)
using MintPlayer.AspNetCore.SpaServices.Xsrf;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
// The header the SPA will send the request token in. Required.
builder.Services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
// Issue the XSRF-TOKEN cookie on every response that gets this far (static files short-circuit above).
// Place it before the endpoints that will be validated and before whatever serves the SPA.
app.UseAntiforgeryGenerator();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
app.Run();
Startup.cs (classic hosting)
using MintPlayer.AspNetCore.SpaServices.Xsrf;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseAntiforgeryGenerator();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
}
}
A validated endpoint
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public IEnumerable<WeatherForecast> Get() => WeatherForecast.Sample();
[HttpPost]
[ValidateAntiForgeryToken] // requires a matching X-XSRF-TOKEN header
public ActionResult CreateWeatherForecast() => Ok();
}
Validate only mutating verbs. GET/HEAD/OPTIONS/TRACE are not validated by [AutoValidateAntiforgeryToken], and putting [ValidateAntiForgeryToken] on a GET action is a good way to break your own app.
Angular: standalone bootstrap (app.config.ts)
XSRF protection is on by default in Angular's HttpClient; withXsrfConfiguration just makes the names explicit and self-documenting.
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withXsrfConfiguration } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withXsrfConfiguration({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN'
}))
]
};
Angular: NgModule bootstrap
import { NgModule } from '@angular/core';
import { HttpClientModule, HttpClientXsrfModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN'
})
]
})
export class AppModule { }
Angular: sending a request
Nothing special is needed in the component — the interceptor adds the header:
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({ selector: 'app-create-forecast', template: '<button (click)="create()">Create</button>' })
export class CreateForecastComponent {
private readonly http = inject(HttpClient);
create() {
this.http.post('/WeatherForecast', {}).subscribe({
error: (err) => console.error(err)
});
}
}
Custom header name
If you change the header, change it in both places and leave the cookie name alone:
services.AddAntiforgery(options => options.HeaderName = "X-CUSTOM-XSRF");
provideHttpClient(withXsrfConfiguration({
cookieName: 'XSRF-TOKEN', // fixed by the middleware — do not change
headerName: 'X-CUSTOM-XSRF' // must match AntiforgeryOptions.HeaderName
}))
Troubleshooting
400 Bad Request: "The required antiforgery header value ... is not present"
The request reached validation with no token header.
- Check that
AntiforgeryOptions.HeaderNameis set. It has no default; without it the framework doesn't look for a header at all. - Check that the SPA's
headerNamematches it exactly (Angular's default isX-XSRF-TOKEN). - Angular only attaches the header to relative or same-origin URLs.
this.http.post('/api/x', ...)gets the header;this.http.post('https://api.example.com/x', ...)does not. If your SPA builds absolute URLs from a<base href>, keep them same-origin with the API. - Angular also skips
GETandHEAD. A validatedGETwill always fail.
400 Bad Request: token mismatch, or "The antiforgery cookie token and request token do not match"
Both tokens arrived but don't pair up.
- The most common cause is a renamed cookie: the SPA is reading
AntiforgeryOptions.Cookie.Nameinstead ofXSRF-TOKEN. Point it back atXSRF-TOKEN. - Tokens are bound to the authenticated identity. If the user signs in or out between the response that issued the cookie and the request that uses it, the pair no longer matches. Because the middleware refreshes
XSRF-TOKENon every response, a plain reload or any subsequent request fixes this — but a SPA holding a stale in-memory copy of the token will not recover, so read it from the cookie at send time (as Angular's interceptor does). - With multiple server instances, make sure the ASP.NET Core Data Protection keys are shared; otherwise instance B can't validate a token issued by instance A.
The XSRF-TOKEN cookie is never set
- Is
app.UseAntiforgeryGenerator()actually reached? Middleware placed after a terminal branch (UseStaticFilesshort-circuiting for a static asset, aMap/UseSpabranch, or an endpoint that already wrote the response) never runs for that request. For static assets that is deliberate — see Where to register it — but it must still sit before whatever serves your SPA's HTML entry point, or the app loads with no cookie and the first mutating request is rejected. - The cookie is written from a
Response.OnStartingcallback, so it appears only on responses that actually start. Requests aborted before headers are flushed get nothing. - Confirm
IAntiforgeryis registered (AddAntiforgery()directly, or viaAddControllersWithViews()/AddMvc()/AddRazorPages()).
The cookie is set but JavaScript can't read it
The middleware writes the cookie with HttpOnly = false precisely so the SPA can read it. If document.cookie doesn't show it, something else is intercepting: a reverse proxy or CDN rewriting Set-Cookie, a cookie-policy middleware, or UseCookiePolicy with a restrictive MinimumSameSitePolicy. Check the raw Set-Cookie response header in the browser's network tab.
HTTPS and SameSite
The cookie is written with Path=/, SameSite=Strict, and Secure whenever the request arrived over HTTPS (CookieSecurePolicy.SameAsRequest). Change either through the configuring overload.
Before 11.0.0-rc.2 the cookie carried neither attribute, and the README claimed "the framework's cookie policy defaults apply". That was wrong: no cookie policy applies unless the application calls
UseCookiePolicy(), so the attributes were simply absent and the browser's ownSameSitedefault took over. See issue #85.
- Behind a TLS-terminating reverse proxy,
Secureis silently absent unless you enable forwarded headers.SameAsRequestis evaluated againstHttpContext.Request.IsHttps, which isfalsewhen nginx, Traefik, or a container ingress terminated the TLS — even though the browser connected over HTTPS. AddUseForwardedHeaderswithForwardedHeaders.XForwardedProto(and setKnownProxies/KnownNetworksfor your topology; the defaults only trust loopback), or setSecurePolicy = CookieSecurePolicy.Always. The middleware logs a warning once per process when it detects this. CookieSecurePolicy.Alwaysis not the default because a browser refuses aSecurecookie from a plain-HTTP origin other thanlocalhost, which would break HTTP-only intranet and LAN-address development outright.- Keep the SPA and the API on the same origin. XSRF-cookie-to-header only works same-origin: with
SameSite=Lax(the ASP.NET Core default) the cookie isn't sent on cross-site requests, and cross-origin JavaScript can't read it either. If you genuinely must split origins, you need a CORS design with credentials,SameSite=None; Secure, andAccess-Control-Allow-Headersincluding your token header — at which point you should reconsider whether cookie-based antiforgery is the right tool. - During development over
http://localhost,SameSite=Nonecookies are rejected by browsers for lackingSecure. Prefer running the dev server over HTTPS (app.UseHttpsRedirection()plus the ASP.NET Core dev certificate) and stay on the same origin. - Behind a TLS-terminating proxy, configure forwarded headers so the app knows the request was HTTPS; otherwise redirect and cookie behaviour will disagree with the browser's view of the connection.
Where to register it
One rule: before whatever serves the SPA's HTML entry point. Angular attaches no antiforgery header until the cookie exists, so if the navigation that loads the app does not mint one, the first mutating request is rejected.
It does not have to come before UseStaticFiles(), and usually should not. Static-file middleware short-circuits for a file it can serve, so anything registered after it never runs for those responses — which is what you want:
app.UseHttpsRedirection();
app.UseStaticFiles(); // fingerprinted assets short-circuit here...
app.UseAntiforgeryGenerator(); // ...so they keep public, max-age=31536000
app.UseRouting();
app.UseEndpoints(/* ... */);
app.UseSpaImproved(/* serves index.html, and does pass through the mint */);
Registered before UseStaticFiles(), every asset response also carries a per-user Set-Cookie: XSRF-TOKEN and has its Cache-Control forced to private (see Caching), so public, max-age=31536000 on a hashed bundle becomes max-age=31536000, private and drops out of shared caches. Correct, but wasteful — the CDN-cacheability of your static assets is decided by where you put this line.
Endpoint-routed static assets
MapStaticAssets() serves from UseEndpoints, so those responses are reached after this middleware wherever you put it — UseStaticFiles short-circuits, an endpoint does not. The lighter way to exempt them, from 11.0.0-rc.3, works wherever the generator is registered:
app.MapStaticAssets().SkipXsrfToken();
See Keeping an endpoint out of the mint. The alternative is to short-circuit the endpoint. Note that short-circuiting also skips authentication, authorization, CORS, rate limiting, output caching and antiforgery validation for those endpoints. For fingerprinted assets that is usually fine. It only keeps the mint away if the generator is registered below UseRouting():
app.UseRouting();
app.UseAntiforgeryGenerator(); // must be BELOW UseRouting
app.UseEndpoints(e => e.MapStaticAssets().ShortCircuit());
The ordering condition is not cosmetic. Short-circuiting takes effect once routing has matched, so it can only skip middleware registered after UseRouting(). Put the generator above it and the middleware has already run and already registered its Response.OnStarting callback — and that callback fires when the response starts regardless of what short-circuited afterwards, so the cookie still goes out and the cache headers are still touched.
Measured on a real server, GET of a short-circuited endpoint:
| Generator | Set-Cookie |
Cache-Control |
|---|---|---|
above UseRouting() |
both cookies written | overwritten by the mint |
below UseRouting() |
none | untouched |
The SPA's HTML entry point is an endpoint too, so it still mints in the second arrangement — the two requirements compose.
Keeping an endpoint out of the mint
Some endpoints serve public, shared-cacheable responses nobody submits a form from: status and coverage badges fetched through an image proxy, Open Graph images, RSS/Atom feeds, sitemap.xml, .well-known/*. Through the mint, each one gets a per-user Set-Cookie, has public forced to private (so the proxy stops caching it), and pays a DataProtection round trip for a token nobody reads.
Mark them instead:
app.MapGet("/badge/{id}", GetBadge)
.SkipXsrfToken()
.RequireRateLimiting("per-ip"); // still runs
var feeds = app.MapGroup("/feeds").SkipXsrfToken(); // every endpoint in the group
feeds.MapGet("/subscribe", Subscribe).SkipXsrfToken(false); // ...except this one
[SkipXsrfToken] // a controller, or a single action
public class OgImageController : ControllerBase
{
[SkipXsrfToken(false)] // the one action that still mints
public IActionResult Editor() { /* ... */ }
}
The most specific metadata wins, as with the framework's [RequireAntiforgeryToken(false)]: an action's attribute beats its controller's, and an endpoint's convention beats its group's. Custom metadata can implement ISkipXsrfTokenMetadata and its Skip property.
The check runs when the response starts, after routing has matched, so it works whether the generator is registered above or below UseRouting(), and every other middleware still runs. Measured on Kestrel, with the generator above UseRouting() and an endpoint declaring public, max-age=300 with a 1-request rate limit:
| 1st request | 2nd request | |
|---|---|---|
| no opt-out | max-age=300, private, two Set-Cookie |
429 |
.ShortCircuit() |
max-age=300, private, two Set-Cookie |
200: the rate limiter was skipped |
.SkipXsrfToken() |
public, max-age=300 untouched, no Set-Cookie |
429 |
What skipping means:
- No token at all. No framework cookie, no
XSRF-TOKEN, no change toCache-ControlorPragma. - No
X-Frame-Options: SAMEORIGINeither. The antiforgery system adds it as a side effect. If an HTML page relied on that for framing protection, set the header yourself. - Validation is unaffected. This turns off issuing a token, not validating one. That is still governed by
DisableAntiforgery()/[RequireAntiforgeryToken]. A skipped endpoint that requires validation still validates; it just hands out no token.
For responses that have no endpoint, such as a custom middleware serving media or a proxied upstream, use a predicate. It runs at the same point, so it can see the endpoint and the status code:
app.UseAntiforgeryGenerator(o => o.ShouldIssue = ctx => !ctx.Request.Path.StartsWithSegments("/media"));
A predicate that throws is logged at Error, and the token is issued. Failing open is the safe side: wrongly minting costs a private downgrade, while wrongly skipping the entry point breaks the SPA. Prefer the endpoint metadata where an endpoint exists, because it sits next to what it describes and does not drift when a route moves. Before 11.0.0-rc.3 the only alternative was app.UseWhen(ctx => ..., b => b.UseAntiforgeryGenerator()).
⚠️ Never skip the SPA's HTML entry point, or an endpoint the SPA calls to refresh its token. The SPA then has no token to send, and every mutating request after it is rejected. That is why skipping is never automatic, not even for a response the application declared
public: prerendered HTML can legitimately bepublic, and only the application can tell it apart from a badge.
Caching
IAntiforgery.GetAndStoreTokens stamps Cache-Control: no-cache, no-store and Pragma: no-cache whenever the response has not started — and inside a Response.OnStarting callback it never has, because the server commits headers only after the callbacks have run. Kestrel also fires those callbacks last-in-first-out, so this middleware, registered early as recommended, gets the final word over everything else in the pipeline.
Before 11.0.0-rc.2 that made every response passing through UseAntiforgeryGenerator() uncacheable, silently, including responses whose caching policy the application had deliberately set — and including prerendered HTML from MintPlayer.AspNetCore.SpaServices.Prerendering, which goes to some trouble to preserve it.
The default is now XsrfCacheHeaderPolicy.PreservePrivate:
| The response had | Result |
|---|---|
No Cache-Control of its own |
no-cache, no-store — unchanged. The SPA's HTML navigation carries a fresh token and is still never cached. |
Cache-Control: public, max-age=300 |
max-age=300, private — preserved, but forced private. |
Cache-Control: no-store |
preserved. |
a Cache-Control that cannot be parsed |
no-cache, no-store. It cannot be made private reliably. From 11.0.0-rc.3 the package logs a Warning naming the dropped value, once per process. |
private is forced and public dropped because the response carries a Set-Cookie holding this user's token; a shared cache storing it could hand that token to the next visitor. Set options.CacheHeaders = XsrfCacheHeaderPolicy.NoStore to restore the pre-11.0.0-rc.2 behaviour. For a response that should stay public, keep it out of the mint altogether: see Keeping an endpoint out of the mint.
DefaultAntiforgery logs "The 'Cache-Control' and 'Pragma' headers have been overridden…" (EventId 8) whenever it finds a caching policy on the response. In 11.0.0-rc.2 that warning appeared once per request on every response with its own Cache-Control, although PreservePrivate had put the policy back. From 11.0.0-rc.3 the package hides the application's headers from the framework while it mints, so the warning no longer appears under PreservePrivate. Under NoStore the override is real, and the warning still appears. If the mint fails, the application's headers are restored exactly as it set them.
What this package does not protect
The framework's own antiforgery cookie ships without
Secure, even over HTTPS.AntiforgeryOptions.Cookie.SecurePolicydefaults toCookieSecurePolicy.None, and that cookie belongs toAddAntiforgery, not to this package. If you serve over HTTPS everywhere, set it yourself:if (!builder.Environment.IsDevelopment()) { builder.Services.AddAntiforgery(options => { options.HeaderName = "X-XSRF-TOKEN"; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; }); }⚠️
CookieSecurePolicy.Alwaysmakes the antiforgery system throw on any plain-HTTP request. Behind a TLS-terminating proxy without forwarded headers, that is every request. The middleware survives it — the response goes out intact, without the cookie, and an error is logged — but antiforgery validation will then fail, so fix the forwarded headers rather than relying on the degradation.Validation. This middleware only issues tokens. Rejecting a request is
[ValidateAntiForgeryToken],[AutoValidateAntiforgeryToken], or a global filter.
.NET 11: the automatic CSRF middleware
.NET 11 adds CsrfProtectionMiddleware, injected automatically by WebApplication.CreateBuilder, which allows same-origin requests on Sec-Fetch-Site and rejects cross-site ones. It does not replace this package. It validates only endpoints carrying IAntiforgeryMetadata with RequiresValidation = true — Blazor SSR, minimal APIs binding form data, and MVC actions with an antiforgery attribute. Per the .NET 10→11 migration guide, endpoints that bind JSON, such as a plain MapPost or a Web API [HttpPost], have no behavioural change.
So a cookie-authenticated JSON API still needs a token, and still needs a way to get it to the SPA. What you gain on .NET 11 is a free extra layer underneath. Token validation stays authoritative: when the app calls app.UseAntiforgery(), the token middleware runs after the CSRF middleware and replaces its verdict.
Angular version note
Angular's interceptor never attaches the token header to a cross-origin request, in any version. It also changed how it recognises same-origin:
| Angular | Rule |
|---|---|
| ≤ 20.0 | Skips any absolute URL — including a same-origin one. |
| ≥ 21.0 | Normalises with new URL(...) and compares origins, so same-origin absolute URLs now get the header. |
Use relative API URLs. That is the only advice that works on every version.
Related Packages
- MintPlayer.AspNetCore.SpaServices - Core SPA services
- MintPlayer.AspNetCore.SpaServices.Abstractions - Interfaces for integrating without the implementation
- MintPlayer.AspNetCore.SpaServices.Prerendering - Prerendering support
- MintPlayer.AspNetCore.SpaServices.Routing - SPA route integration
License
This project is licensed under the Apache 2.0 License.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- MintPlayer.SourceGenerators.Attributes (>= 10.20.1)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on MintPlayer.AspNetCore.SpaServices.Xsrf:
| Package | Downloads |
|---|---|
|
MintPlayer.Spark
Low-code .NET framework for building data-driven web applications with minimal boilerplate. Uses PersistentObject pattern to eliminate DTOs and repository layers. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 11.0.0 | 821 | 11/16/2026 |
| 11.0.0-rc.6 | 59 | 11/13/2026 |
| 11.0.0-rc.5 | 63 | 11/7/2026 |
| 11.0.0-rc.4 | 69 | 10/24/2026 |
| 11.0.0-rc.3 | 1,885 | 10/4/2026 |
| 11.0.0-rc.2 | 79 | 9/24/2026 |
| 11.0.0-rc.1 | 79 | 9/17/2026 |
| 10.8.1 | 86 | 11/13/2026 |
| 10.7.1 | 165 | 9/5/2026 |
| 10.7.0 | 130 | 9/3/2026 |
| 10.2.2 | 137 | 8/27/2026 |
| 10.2.1 | 220 | 1/19/2026 |
| 10.2.0 | 177 | 1/18/2026 |
| 10.1.0 | 178 | 1/16/2026 |
| 10.0.0 | 386 | 11/13/2025 |
| 10.0.0-rc.6 | 290 | 11/11/2025 |
| 10.0.0-rc.5 | 285 | 11/11/2025 |
| 10.0.0-rc.4 | 205 | 11/5/2025 |
| 10.0.0-rc.1 | 185 | 10/2/2025 |
| 9.0.0 | 282 | 11/13/2024 |
v 11.0.0-rc.3
FIXES
- DefaultAntiforgery no longer logs "The 'Cache-Control' and 'Pragma' headers have been
overridden..." (EventId 8) once per request on every response that sets its own caching policy.
Under PreservePrivate that message was false: the policy was put back straight afterwards. The
middleware now hides the application's headers from the framework while it mints, and restores
them afterwards. Response headers are unchanged. Under NoStore the override is real, and the
warning still appears.
- A failed mint now restores the application's Cache-Control and Pragma exactly as it set them. If
a replaced IAntiforgery wrote a cookie before throwing, the restored value is forced private.
- An application Cache-Control that cannot be parsed, and is therefore replaced with
"no-cache, no-store", is now reported by a Warning naming the value, logged once per process.
Before, the policy was dropped silently. The middleware now writes the no-store pair itself, so
a replaced IAntiforgery that stamps no cache headers no longer leaves the response without one.
FEATURES
- [SkipXsrfToken] on a controller or action, and .SkipXsrfToken() on a minimal-API endpoint or
route group (any IEndpointConventionBuilder), keep that response out of the mint: no cookie, no
change to Cache-Control or Pragma, no X-Frame-Options. Unlike ShortCircuit(), authentication,
authorization, CORS, rate limiting and every other middleware still run. The metadata is read
when the response starts, so it works whether the generator is registered above or below
UseRouting(). The most specific metadata wins, so [SkipXsrfToken(false)] on an action, or
.SkipXsrfToken(false) on an endpoint, re-enables the mint inside a skipped controller or group.
Custom metadata can implement ISkipXsrfTokenMetadata (bool Skip). This turns off issuing a
token, not validating one. Never apply it to the SPA's HTML entry point or token-refresh endpoint.
- XsrfOptions.ShouldIssue (Func<HttpContext, bool>?, default null = always) does the same per
response for responses with no endpoint. A predicate that throws is logged at Error and fails
open: the token is issued, because wrongly skipping the SPA's entry point is the costlier mistake.
DOCUMENTATION
- New README section "Keeping an endpoint out of the mint". "Endpoint-routed static assets" now
recommends MapStaticAssets().SkipXsrfToken() and lists what ShortCircuit() additionally skips.
v 11.0.0-rc.2
BREAKING CHANGES
- The XSRF-TOKEN cookie is now written with SameSite=Strict and with Secure on HTTPS requests
(CookieSecurePolicy.SameAsRequest). Both were previously absent, so the browser applied its own
SameSite default and the token travelled in clear over plain HTTP. If your SPA is served from a
different site than the API, review SameSite before upgrading; configure it through the new
UseAntiforgeryGenerator(options => ...) overload.
- Cache-Control and Pragma set by your application now survive the token mint. Previously every
response through this middleware became "no-cache, no-store", because IAntiforgery stamps those
headers whenever the response has not started and this middleware runs at exactly that moment.
A preserved Cache-Control is forced to "private" - the response carries a Set-Cookie, so it must
never be stored by a shared cache. Responses that set no Cache-Control of their own still get
"no-cache, no-store", as does a Cache-Control that cannot be parsed - a malformed value cannot be
made safe, and prefixing "private" onto it could emit "private, public, ..." with no defined
winner. A Pragma the application set is preserved even when it set no Cache-Control. Set
options.CacheHeaders = XsrfCacheHeaderPolicy.NoStore for the old behaviour.
FIXES
- A failure while issuing the token no longer destroys the response. Kestrel catches outside its
OnStarting loop, so a throw here abandoned every remaining callback and produced a bare 500 with
every header reset - including Set-Cookie - which UseExceptionHandler could not see. The mint now
degrades to "no cookie on this response" and logs an error. This was reachable in production:
AntiforgeryOptions.Cookie.SecurePolicy = Always throws on a plain-HTTP request, which is what a
TLS-terminating reverse proxy looks like without UseForwardedHeaders.
- A null RequestToken no longer throws. Unreachable with the built-in IAntiforgery, but it took the
whole response with it when a replacement returned one.
- The middleware warns once when it writes the cookie without Secure outside of Development,
naming UseForwardedHeaders - the case where a proxy terminates TLS and Request.IsHttps is false.
- IAntiforgery is resolved per request instead of once from the root provider, so a scoped
decorator over it is no longer captured for the lifetime of the application.
FEATURES
- New overload UseAntiforgeryGenerator(Action<XsrfOptions>) configuring the cookie name, path,
SameSite, SecurePolicy and the cache-header policy. Configurations that cannot work - an HttpOnly
cookie the SPA could not read, SameSite=None without Secure - are rejected at startup rather than
diagnosed later from a 400. XsrfOptions.Cookie is get-only by design: set its properties
(options.Cookie.Name = "...") rather than assigning a new CookieBuilder, which would silently
reset SameSite to Unspecified and reintroduce the defect this release fixes.
DOCUMENTATION
- The README claimed the cookie was written "without Secure or an explicit SameSite value, so the
framework's cookie policy defaults apply". No cookie policy applies unless the application calls
UseCookiePolicy; the attributes were simply absent.
- New "Where to register it" section. The old advice was "register early, before static files",
which is stronger than necessary: the real rule is "before whatever serves the SPA's HTML entry
point". Putting it after UseStaticFiles lets fingerprinted assets short-circuit, so they keep
their public, max-age=... instead of being given a per-user Set-Cookie and downgraded to private.
Also covers MapStaticAssets, which is served from UseEndpoints and so is reached after this
middleware wherever it sits: exempting it needs ShortCircuit() on the endpoint AND the
generator registered below UseRouting, because short-circuiting can only skip middleware
registered after the route match. Verified on a real server rather than taken from the docs.
- Documented that AntiforgeryOptions.Cookie.SecurePolicy defaults to None, so the framework's own
antiforgery cookie ships without Secure even over HTTPS, and that this package cannot fix it.
v 10.2.2
DOCUMENTATION
- The README told you to call app.UseSpaXsrf(), which does not exist. The method is
app.UseAntiforgeryGenerator().
- The README claimed support for custom header and cookie names. The cookie name is XSRF-TOKEN and
is not configurable; the header name is set through the standard services.AddAntiforgery(...)
options, not by this package.