Cookie authentication is convenient for browser applications built with ASP.NET Core. After a user signs in, the browser automatically attaches the authentication cookie to subsequent requests. That convenience also creates a security responsibility: state-changing requests may be vulnerable to Cross-Site Request Forgery (CSRF).
In a CSRF attack, a malicious website attempts to make a browser send a request to another application where the user is already authenticated. Because the browser automatically includes the target application’s cookie, the server may process the request as if it came from the user’s own interface. This article explains how to recognize the problem, implement antiforgery protection, and decide when an endpoint can safely opt out.
Start by identifying how credentials are transported
CSRF is primarily a concern when the browser sends the authentication credential automatically. Cookie authentication has this property. A bearer token or API key placed explicitly in an Authorization or custom header is not normally added by the browser to an arbitrary cross-site request.
| Authentication method | Automatically sent by the browser? | Antiforgery consideration |
|---|---|---|
| Cookie authentication | Yes | Usually required for state-changing browser requests |
| Authorization: Bearer | No | Usually not required for classic CSRF protection |
| API key header | No | Usually not required for classic CSRF protection |
This is why the statement “it is an API, so CSRF does not apply” is unsafe. An endpoint can return JSON and still need CSRF protection if the browser authenticates with a cookie and can call the endpoint from a web page.
A concrete problem: a cookie-authenticated order API
Consider an e-commerce application where an authenticated user creates an order by calling POST /api/orders. The endpoint is protected with authorization, but no antiforgery validation is configured:
[ApiController]
[Route("api/orders")]
[Authorize]
public class OrdersController : ControllerBase
{
[HttpPost]
public IActionResult Create(CreateOrderRequest request)
{
// Create the order
return Ok();
}
}After the user signs in, a malicious site could submit a form or trigger a request to the order endpoint. The browser attaches the authentication cookie automatically. The server sees an authenticated request, even though the request did not originate from the application’s own interface. The [Authorize] attribute verifies identity and access; it does not verify the request’s origin.
How token-based antiforgery protection works
Antiforgery protection requires a value that the attacker’s site cannot read or predict. A common arrangement uses two related values:
- An antiforgery cookie issued by the application.
- A request token sent in a form field or a dedicated HTTP header.
The malicious site may cause the browser to send cookies, but same-origin restrictions prevent it from reading the token generated by the target application. Without the matching request token, the state-changing request fails validation.
Protecting MVC and Razor Pages actions
Traditional MVC and Razor Pages applications can use the built-in antiforgery attributes. For a modifying action, explicit validation is straightforward:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult UpdateProfile(UpdateProfileModel model)
{
if (!ModelState.IsValid)
return View(model);
// Update the profile
return RedirectToAction("Index");
}For applications where most controller actions are browser-facing, AutoValidateAntiforgeryToken is often a better default. It requires tokens for unsafe HTTP methods while avoiding token requirements for safe methods such as GET. This does not make a state-changing GET safe. GET actions should remain read-only because caches, crawlers, prefetchers, and links can invoke them unexpectedly.
Sending the token from a JavaScript client
Single-page applications and pages that use fetch commonly send JSON instead of submitting HTML forms. In that case, configure a header name and expose a request token to the JavaScript client:
builder.Services.AddAntiforgery(options =>
{
options.HeaderName = "X-XSRF-TOKEN";
});
var app = builder.Build();
app.MapGet("/security/antiforgery-token", (IAntiforgery antiforgery, HttpContext context) =>
{
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append(
"XSRF-TOKEN",
tokens.RequestToken!,
new CookieOptions
{
HttpOnly = false,
Secure = true,
SameSite = SameSiteMode.Lax
});
return Results.Ok();
}).RequireAuthorization();The client first obtains the token and then sends it in the configured header:
await fetch("/security/antiforgery-token", {
credentials: "include"
});
await fetch("/api/orders", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-XSRF-TOKEN": readCookie("XSRF-TOKEN")
},
body: JSON.stringify(order)
});The token cookie must be readable by JavaScript in this pattern, so it uses HttpOnly=false. This is not the authentication cookie. Exposing the authentication cookie to JavaScript would increase the impact of an XSS vulnerability and should not be used as a substitute for a request token.
Configuring antiforgery in Minimal APIs
Registering antiforgery services does not always mean that the middleware has been added explicitly. For Minimal API applications, configure the relevant services and pipeline deliberately:
builder.Services.AddAntiforgery(options =>
{
options.HeaderName = "X-XSRF-TOKEN";
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.MapPost("/api/orders", (CreateOrderRequest request) =>
{
return Results.Ok();
}).RequireAuthorization();Placing antiforgery processing after authentication and authorization provides a predictable pipeline, especially for endpoints that read form data. Form-binding behavior and automatic antiforgery requirements can vary by endpoint type and ASP.NET Core version, so verify the behavior of the target framework rather than assuming that every JSON endpoint is treated like a form endpoint.
When an endpoint can opt out
A webhook or internal service endpoint protected exclusively by a bearer token, API key, or another explicit non-cookie credential may not need browser-oriented CSRF validation. Such an endpoint can opt out when the security decision is intentional:
app.MapPost("/api/webhooks/payment", (PaymentNotification notification) =>
{
return Results.Accepted();
}).DisableAntiforgery();Do not apply this exception to browser-accessible endpoints that rely on cookies. The opt-out is appropriate only when the endpoint is not vulnerable to ambient browser credentials, such as a server-to-server webhook that requires a signed request or bearer token. Document the reason for every opt-out so that a future change to authentication does not silently reintroduce a vulnerability.
Why SameSite and CORS are not complete replacements
The SameSite cookie attribute can reduce cross-site cookie sending, but it should not be treated as the only CSRF defense for every browser and integration scenario. CORS controls which origins may read responses through browser JavaScript; a CSRF attack does not always require the attacker to read the response. If an unwanted request can change server-side state, antiforgery validation remains important for cookie-authenticated endpoints.
For cross-origin SPAs, list trusted origins explicitly, avoid wildcard policies with credentials, and allow credentialed requests only where required. The endpoint that issues the antiforgery token must follow the same origin and authentication rules as the protected API.
Test the security boundary
- Send a POST request with the authentication cookie but without the antiforgery token and verify that it is rejected.
- Modify the header token and confirm that validation fails.
- Send the valid cookie and matching header token and confirm that the operation succeeds.
- Verify that GET requests do not modify state.
- Confirm that a bearer-token webhook has a documented reason for opting out.
- Check that production antiforgery cookies are transmitted over HTTPS.
Conclusion
In ASP.NET Core, CSRF protection for an API depends less on whether the endpoint returns JSON and more on how the browser authenticates. If a browser automatically sends a cookie, state-changing requests should normally use antiforgery validation, secure cookie settings, a narrowly defined CORS policy, and correct HTTP semantics.
A practical design is to apply broad antiforgery validation to MVC and Razor Pages, send request tokens in a dedicated header from JavaScript clients, configure the Minimal API pipeline explicitly, and allow opt-outs only for endpoints that do not rely on ambient cookie credentials. This approach keeps the security decision close to the endpoint and makes future maintenance safer.
Sources
- https://learn.microsoft.com/aspnet/core/security/anti-request-forgery?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/security/authentication/api-endpoint-auth?view=aspnetcore-3.1
- https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-8.0
- https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca5391
0 Comments