CSRF mechanics, when cookie authentication is exposed, ASP.NET Core antiforgery across MVC, Razor Pages, Minimal APIs and SPAs, and the limits of SameSite cookies.
CSRF makes a victim's browser send a state-changing request to your site from another site; it works because the browser attaches cookies automatically. If you authenticate with cookies, you're exposed; if callers send a bearer token in the Authorization header, a cross-site page can't add it, so classic CSRF doesn't apply.
ASP.NET Core's antiforgery uses a synchroniser token: a cookie token plus a token in the form or a header, validated together. MVC forms get it from the form tag helper with [ValidateAntiForgeryToken] or the global auto-validate filter; Razor Pages validate POSTs by default; Minimal APIs need AddAntiforgery/UseAntiforgery and validate form-bound endpoints. SameSite=Lax (the default for ASP.NET Core auth cookies) blocks most cross-site POSTs, but not attacks from a sibling subdomain or GETs that change state, so keep tokens.
"CSRF is confused-deputy: my site trusts the browser because it carries the session cookie, and the browser will carry that cookie on a request that some other site started. A hidden auto-submitting form on
evil.exampleposting to/account/emailis enough if I rely on cookies and nothing else. So the first question I ask is how the app authenticates. If it's a cookie, I need CSRF protection. If it's a pure API where clients put a bearer token in theAuthorizationheader, a cross-site page can't attach that header, so CSRF isn't the risk; XSS is.ASP.NET Core's answer is the synchroniser token pattern.
IAntiforgeryissues a cookie token and a request token derived from the same secret, bound to the user, and protected with Data Protection. The form tag helper writes the request token as a hidden field, and validation checks the pair. In MVC I addAutoValidateAntiforgeryTokenAttributeglobally so every unsafe method is covered. Razor Pages does it by default. Minimal APIs since .NET 8 haveUseAntiforgery, which validates endpoints that bind forms. For a SPA using cookie auth through a BFF, I expose the token through a readable cookie and the client echoes it in anX-XSRF-TOKENheader. For example, at [company] we [moved our SPA to a BFF with cookies] and the first security review asked exactly this; header-based antiforgery closed it with [one middleware and an Axios interceptor].The mistake I see is 'we have SameSite=Lax, we don't need tokens'. Lax blocks cross-site POSTs, but
shop.example.com.auandblog.example.com.auare the same site, so a takeover of any subdomain bypasses it, and a GET that changes state is still exposed. SameSite is a great second layer, not the first."
| Authentication | CSRF risk | Why |
|---|---|---|
| Cookie (MVC, Razor Pages, BFF) | Yes | Browser sends cookies automatically |
Bearer token in Authorization header |
No (classic CSRF) | Cross-site pages can't set that header |
| Windows/Kerberos/NTLM, client certificates | Yes | Also ambient credentials |
| Basic auth cached by the browser | Yes | Ambient |
app.MapPost("/account/email", ([FromForm] string email, ...) => ...).DisableAntiforgery(); behind cookie auth, or an MVC action with [IgnoreAntiforgeryToken].email=attacker@... to /account/email; the victim's cookie rides along.DisableAntiforgery, call UseAntiforgery(), and render the token in the form (or send it in a header from the SPA).| Model | What's automatic | What you do |
|---|---|---|
| MVC | Form tag helper emits the token | Add AutoValidateAntiforgeryTokenAttribute globally |
| Razor Pages | Token emitted and validated for POST | Nothing (don't add IgnoreAntiforgeryToken) |
| Minimal APIs (.NET 8+) | Validates endpoints binding [FromForm]/IFormFile once UseAntiforgery runs |
Call AddAntiforgery/UseAntiforgery; for JSON + cookies validate explicitly |
| Blazor Web App | <AntiforgeryToken /> in forms |
Keep UseAntiforgery after auth |
| SPA + BFF | — | Header token (X-XSRF-TOKEN) + IAntiforgery.ValidateRequestAsync |
In a BFF rollout, adding header-based antiforgery and SameSite=Strict on the session cookie cost one extra cookie and a 10-line Axios interceptor; an OWASP ZAP scan that had flagged 14 state-changing endpoints for missing anti-CSRF tokens reported none afterwards.
Checks that the candidate links CSRF to ambient credentials, knows ASP.NET Core antiforgery across app models, and understands SameSite's limits.
Green flags
Red flags
Victim logged in to bank.example.com.au (session cookie set)
|
| visits evil.example
v
<form action="https://bank.example.com.au/transfer" method="post"> ... auto-submit
|
v
Browser POSTs to bank, attaching the bank cookie (if SameSite allows)
|
v
Bank sees a valid session -> performs the transfer
The attacker never sees the response; they only need the side effect. CORS doesn't stop it, because a form POST with application/x-www-form-urlencoded is a simple request and is sent without a preflight.
IAntiforgery (DefaultAntiforgery) generates:
.AspNetCore.Antiforgery.<id>), HttpOnly, containing a random security token;Both are encrypted with Data Protection (purpose Microsoft.AspNetCore.Antiforgery.AntiforgeryToken.v1). On validation, both are decrypted and compared. An attacker's site can make the browser send the cookie but can't read your page to get the request token, because the same-origin policy hides the response. That's the whole trick, and it's why XSS (which runs in your origin) defeats it.
This is also why antiforgery fails across instances when Data Protection keys aren't shared: the token was encrypted by another instance's key ring.
AddAntiforgery() registers the services; UseAntiforgery() adds middleware that, for endpoints with antiforgery metadata, validates the request. Endpoints that bind [FromForm] or IFormFile get that metadata automatically. JSON endpoints don't, because the assumption is they're called with bearer tokens; if a JSON endpoint is cookie-authenticated, validate explicitly with IAntiforgery.ValidateRequestAsync or an endpoint filter. UseAntiforgery must come after UseAuthentication and UseAuthorization.
| SameSite | Cross-site POST | Top-level cross-site GET navigation | Same-site subdomain |
|---|---|---|---|
| Strict | Not sent | Not sent | Sent |
| Lax | Not sent | Sent | Sent |
| None (+Secure) | Sent | Sent | Sent |
ASP.NET Core's cookie authentication defaults to SameSite=Lax. Gaps: 'site' means registrable domain, so evil.example.com.au owned by a compromised subdomain is same-site; GET handlers with side effects are reachable via a link; and Chromium's 'Lax-by-default' for cookies without an explicit attribute allowed top-level cross-site POSTs for two minutes after the cookie was set, a known bypass window.
Origin isn't yours; good as an extra layer.Sec-Fetch-Site: cross-site): modern browsers send it; a resource isolation policy can reject cross-site unsafe requests.UseAntiforgery.Lax, Strict and None and repeat the attack.Sec-Fetch-Site on same-origin and cross-site requests in dev tools.Antiforgery for a cookie-authenticated app: global validation for MVC, Minimal API form endpoints, and header-based tokens for an SPA served by the same BFF.
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication("Cookies").AddCookie("Cookies", o =>
{
o.Cookie.HttpOnly = true;
o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
o.Cookie.SameSite = SameSiteMode.Strict; // second layer, not the only one
});
builder.Services.AddAuthorization();
builder.Services.AddAntiforgery(o => o.HeaderName = "X-XSRF-TOKEN");
builder.Services.AddControllersWithViews(o =>
o.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())); // every POST/PUT/PATCH/DELETE
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery(); // after auth
// Give the SPA a readable token cookie (the cookie token itself stays HttpOnly)
app.MapGet("/bff/antiforgery", (IAntiforgery af, HttpContext ctx) =>
{
var tokens = af.GetAndStoreTokens(ctx);
ctx.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken!,
new CookieOptions { HttpOnly = false, Secure = true, SameSite = SameSiteMode.Strict });
return Results.NoContent();
}).RequireAuthorization();
// JSON endpoint authenticated by cookie: validate explicitly
app.MapPost("/bff/account/email", async (EmailChange body, IAntiforgery af, HttpContext ctx, CancellationToken ct) =>
{
await af.ValidateRequestAsync(ctx); // throws AntiforgeryValidationException -> 400
// ... change the email
return Results.NoContent();
}).RequireAuthorization();
// Form endpoint: validated automatically because it binds [FromForm]
app.MapPost("/newsletter", ([FromForm] string email) => Results.Ok()).RequireAuthorization();
app.MapDefaultControllerRoute();
app.Run();
public sealed record EmailChange(string NewEmail);
// SPA: Axios echoes the token cookie into the header on unsafe requests
axios.defaults.xsrfCookieName = 'XSRF-TOKEN';
axios.defaults.xsrfHeaderName = 'X-XSRF-TOKEN';
axios.defaults.withXSRFToken = true;
[IgnoreAntiforgeryToken] or DisableAntiforgery() to 'fix' 400 errors. Why it is wrong: it removes the protection instead of fixing the client. Instead: send the token from the form or header, and fix Data Protection key sharing if it fails across instances./orders/42/cancel via link). Why it is wrong: Lax cookies are sent on top-level GET navigation and antiforgery isn't validated for GET. Instead: use POST/PUT/DELETE for side effects.UseAntiforgery. Why it is wrong: only form-binding endpoints get antiforgery metadata automatically. Instead: validate explicitly when JSON endpoints use cookie auth.The senior question is 'what credential does the browser send without being asked?' If the answer is nothing (bearer tokens in headers), CSRF largely disappears and XSS becomes the threat to tokens. If the answer is a cookie (which the BFF pattern deliberately chooses, to keep tokens out of JavaScript), CSRF protection is mandatory, and you layer it: antiforgery token, SameSite=Strict or Lax, Origin or Fetch-Metadata checks, and re-authentication for high-value actions.
| Defence | When it fits | Cost | Limitation |
|---|---|---|---|
| Synchroniser token (IAntiforgery) | Any cookie-authenticated app | Token plumbing, Data Protection key sharing | Defeated by XSS |
| SameSite=Strict | Session cookies of apps not entered via cross-site links | Users arriving from emails appear logged out on first request | Same-site subdomains |
| SameSite=Lax | Default for most apps | None | GET side effects, subdomains |
| Origin / Sec-Fetch-Site checks | Extra layer for APIs and BFFs | Small middleware | Older clients may omit headers |
| Re-authentication | Payments, credential changes | User friction | Only for high-value actions |
Measure: count of endpoints with antiforgery disabled (should be near zero and justified), antiforgery validation failures in logs (a spike means a client bug or an attack), and ZAP findings.
After a successful login the app calls HttpContext.SignInAsync: the cookie handler serialises the ClaimsPrincipal into an authentication ticket, encrypts and signs it with Data Protection, and sends it as a cookie. On each request the handler decrypts the cookie and rebuilds HttpContext.User, with no database call.
HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).ExpireTimeSpan (default 14 days) with sliding expiration that reissues the cookie once half the window has passed; IsPersistent decides whether it survives closing the browser.The trade-off: a self-contained cookie is fast and stateless, but you can't revoke it without extra checks or a server-side ticket store.
Put a single identity provider in the middle (Entra External ID, Auth0 or a self-hosted OIDC server) that federates Google and Apple; every app speaks only OIDC to it, so adding a login provider never touches your code.
HttpOnly, SameSite cookie; it proxies API calls with an access token.The trade-off: a BFF adds a hop and state, in exchange for no tokens in the browser.
How to tell it (STAR)
**S:** At [company] we moved our SPA to a BFF with a session cookie, and the next pen test flagged [14] endpoints as CSRF-vulnerable with a working PoC. **T:** I had to close it before [the go-live date] without breaking the client. **A:** I found the cookie was `SameSite=None` for a legacy iframe and that nothing validated tokens on JSON routes. I switched to Lax as an immediate block, then added header-based antiforgery through an endpoint filter, an Axios interceptor and an Origin check. **R:** The retest showed zero CSRF findings, the change was [about 50 lines], and our pipeline now fails if a cookie-authenticated unsafe endpoint skips validation.
Last updated 23 Nov 2026.