Single-page applications (SPAs) use JavaScript frameworks such as React, Angular, and Vue to communicate with backend APIs. These applications often use cookie-based authentication to maintain a user's login session. Although cookies provide a convenient authentication mechanism, they introduce a security risk that developers must understand: Cross-Site Request Forgery (CSRF).
A CSRF attack occurs when a malicious website tricks a user's browser into sending an unwanted request to another website where the user is already authenticated. Because browsers automatically attach matching cookies to requests, the target application may process the request as if the user had intentionally submitted it.
For example, imagine a user is logged in to an online banking application. The application stores an authentication cookie in the browser. The user then visits a malicious website that attempts to submit a money-transfer request to the banking application. If the browser sends the authentication cookie and the application does not validate the request's origin or an antiforgery token, the application might process the request using the user's authenticated session.
ASP.NET Core provides built-in antiforgery services to protect applications from this type of attack. These services can be used with MVC controllers, Razor Pages, and JavaScript-based SPAs.
This article explains how CSRF attacks work, how antiforgery tokens protect ASP.NET Core applications, and how to integrate them with a React or Angular frontend using cookie-based authentication.
Understanding Cross-Site Request Forgery
Cross-Site Request Forgery is an attack that abuses the trust between a web application and an authenticated user's browser.
When a user signs in to an application, the server may issue an authentication cookie. The browser stores that cookie and automatically sends it with subsequent requests to the matching website.
The browser does not automatically know whether a request was initiated by the application's own interface or by an external website.
Consider the following example.
A banking application provides an endpoint:
POST /api/transfers
Content-Type: application/jsonThe endpoint accepts a transfer request:
{
"recipientAccount": "9876543210",
"amount": 5000
}The user is already authenticated through a cookie. If the application accepts state-changing requests without additional CSRF protection, an attacker may try to make the browser submit an unwanted request.
A malicious page could attempt a cross-origin form submission such as:
<form
action="https://bank.example.com/api/transfers"
method="POST">
<input
type="hidden"
name="recipientAccount"
value="9876543210">
<input
type="hidden"
name="amount"
value="5000">
<button type="submit">Continue</button>
</form>The attacker cannot normally read the response because of browser same-origin restrictions. However, reading the response is not necessary for a CSRF attack. The objective is to make the authenticated browser send an unwanted request.
This is why protecting state-changing endpoints is important.
Why cookie-based authentication creates a CSRF risk
Cookies are automatically included by browsers when requests match their domain, path, and security rules.
This behavior is useful for authentication because applications do not need to manually attach a session cookie to every request. However, it also means an external website may be able to cause the browser to send a request with the user's authentication cookie.
A CSRF attack generally requires:
The victim to be authenticated to the target application.
The browser to automatically include the authentication cookie.
The application to accept the unwanted request.
The application to lack sufficient CSRF validation.
CSRF protection is particularly important for endpoints that create, update, or delete data.
What Is an Antiforgery Token?
An antiforgery token is a security value used to verify that a state-changing request originated from a trusted application context.
ASP.NET Core uses a token-pair approach. The application generates an antiforgery cookie token and a separate request token.
The browser sends the cookie token automatically. The frontend JavaScript reads the request token and sends it in a custom HTTP header.
The server validates both values before allowing the protected operation to continue.
A typical request looks like this:
POST /api/profile/update HTTP/1.1
Content-Type: application/json
Cookie: .AspNetCore.Antiforgery=...
X-CSRF-TOKEN: request-token-value
{
"displayName": "John"
}The authentication cookie identifies the user. The antiforgery cookie and request token provide an additional check that the request was created through the expected application flow.
An attacker on another website may be able to cause the browser to send the authentication cookie, but the attacker should not be able to read the request token from the trusted application's origin and attach it to the malicious request.
The antiforgery token is not an authentication token. It does not identify the user or replace authorization checks.
Configure Antiforgery in ASP.NET Core
ASP.NET Core provides the IAntiforgery service and AddAntiforgery extension method for configuring antiforgery protection.
The first step is to register the service and configure the header name that the frontend will use.
Open Program.cs and add the following configuration:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddAuthentication();
builder.Services.AddAuthorization();
builder.Services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN";
options.Cookie.Name = "__Host-AppAntiforgery";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy =
CookieSecurePolicy.Always;
options.Cookie.SameSite =
SameSiteMode.Strict;
});
var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();This example configures the antiforgery header and cookie.
The HeaderName property tells ASP.NET Core where to look for the request token. The frontend must use the same header name when sending protected requests.
The antiforgery cookie is marked as HttpOnly, which prevents JavaScript from reading it directly. The request token is obtained separately and provided to the frontend.
The __Host- cookie prefix has additional browser requirements: the cookie must be secure, use the root path, and must not specify a domain. ASP.NET Core's default cookie path is /. If the application is hosted under a subpath or needs a different cookie configuration, choose a suitable cookie name and settings instead.
The SameSite setting should match the application's deployment architecture. Strict provides strong restrictions on cross-site cookie sending, but it can affect legitimate navigation and authentication flows. Lax may be more appropriate for some applications. Cross-site cookie scenarios generally require SameSite=None and Secure.
For production applications, use HTTPS and review the cookie settings based on the actual frontend and API domains.
Generate Antiforgery Tokens for a SPA
A traditional MVC application can generate antiforgery tokens inside Razor views. A JavaScript-based SPA needs another way to obtain the request token.
ASP.NET Core provides the IAntiforgery interface, which includes the GetAndStoreTokens method.
Create an endpoint that generates the token pair and returns the request token to the frontend.
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/security")]
public class SecurityController : ControllerBase
{
private readonly IAntiforgery _antiforgery;
public SecurityController(
IAntiforgery antiforgery)
{
_antiforgery = antiforgery;
}
[HttpGet("antiforgery-token")]
public IActionResult GetAntiforgeryToken()
{
var tokens = _antiforgery.GetAndStoreTokens(
HttpContext);
Response.Headers.CacheControl = "no-store";
return Ok(new
{
requestToken = tokens.RequestToken
});
}
}When the endpoint is called, ASP.NET Core generates the antiforgery tokens and stores the cookie token in the response. The request token is returned in the JSON response.
The frontend should keep the request token in memory and attach it to subsequent state-changing requests.
This endpoint does not need to expose the antiforgery cookie value. The browser handles that cookie automatically.
For an application that uses cookie authentication, the token endpoint can be available after login or before login, depending on the application flow. If the endpoint is protected by authorization, the frontend must authenticate before requesting the token.
The token endpoint should not be cached by browsers, proxies, or CDNs. The Cache-Control: no-store header helps prevent accidental caching of the response.
Validate Antiforgery Tokens in ASP.NET Core APIs
Generating a token is only one part of the implementation. The API must validate the token before processing a state-changing request.
For MVC controllers, ASP.NET Core provides two commonly used attributes:
ValidateAntiForgeryTokenAutoValidateAntiforgeryToken
The ValidateAntiForgeryToken attribute requires a valid antiforgery token for the action to execute.
The AutoValidateAntiforgeryToken attribute validates unsafe HTTP methods while excluding GET, HEAD, OPTIONS, and TRACE.
For MVC applications that use cookie authentication, applying automatic validation globally is a useful approach.
builder.Services.AddControllers(options =>
{
options.Filters.Add(
new AutoValidateAntiforgeryTokenAttribute());
});The configuration ensures that unsafe controller actions are protected by default.
For a specific controller, the attribute can also be applied directly:
[ApiController]
[Route("api/profile")]
[AutoValidateAntiforgeryToken]
public class ProfileController : ControllerBase
{
[HttpPost("update")]
public IActionResult UpdateProfile(
UpdateProfileRequest request)
{
return Ok(new
{
message = "Profile updated successfully"
});
}
}When a request reaches the action, ASP.NET Core validates the antiforgery cookie and request token. If validation fails, the action is not executed.
For applications that use AddControllers without MVC views, explicitly configuring the filter is important. Calling AddControllers alone does not enable the MVC antiforgery filter by default.
Minimal APIs require a different integration approach. MVC action filters do not automatically apply to Minimal API endpoints. For Minimal APIs, use the antiforgery services and endpoint metadata or explicitly validate tokens through IAntiforgery.ValidateRequestAsync.
Do not assume that adding AddAntiforgery automatically protects every API endpoint.
Integrate Antiforgery Protection With React
React applications usually communicate with backend APIs through fetch, Axios, or another HTTP client.
The frontend first requests an antiforgery token. It then includes that token in a custom header whenever it sends a state-changing request.
Join the conversation! Your thoughts help the community grow.