Using ASP.NET Core Antiforgery to Protect Single-Page Applications

JavaScript frameworks like React, Angular, and Vue are used by single-page applications (SPAs) to interact with backend APIs. Cookie-based authentication is frequently used by these programs to keep users logged in. Cookies offer a practical authentication method, but they also present a security risk that developers need to be aware of: Cross-Site Request Forgery (CSRF).

When a malicious website deceives a user’s browser into sending an undesired request to another website where the user has previously authenticated, this is known as a cross-site request forgery (CSRF) attack. The destination application may handle the request as if the user had purposefully sent it as browsers automatically attach matching cookies to requests.

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/json

The 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:

  • ValidateAntiForgeryToken
  • AutoValidateAntiforgeryToken

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.

The following example uses the browser Fetch API.

Get the antiforgery token

let csrfToken = null;

async function loadAntiforgeryToken() {
    const response = await fetch(
        "https://localhost:7001/api/security/antiforgery-token",
        {
            method: "GET",
            credentials: "include"
        }
    );

    if (!response.ok) {
        throw new Error(
            "Unable to obtain antiforgery token"
        );
    }

    const data = await response.json();

    csrfToken = data.requestToken;
}

The credentials: "include" option allows the browser to send and receive cookies when the API is on a different origin. For same-origin requests, the default Fetch credentials mode is same-origin, so this option is not necessary.

Send a protected request

After obtaining the token, include it in the request header.

async function updateProfile(profile) {
    if (!csrfToken) {
        await loadAntiforgeryToken();
    }

    const response = await fetch(
        "https://localhost:7001/api/profile/update",
        {
            method: "POST",
            credentials: "include",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": csrfToken
            },
            body: JSON.stringify(profile)
        }
    );

    if (!response.ok) {
        throw new Error(
            "Profile update failed"
        );
    }

    return await response.json();
}

The browser sends the authentication and antiforgery cookies automatically when the cookie rules allow it. The JavaScript code sends the request token in the custom header.

The API validates the token pair before processing the profile update.

Handle token expiration and authentication changes

Antiforgery tokens can become invalid when the authentication context changes or the associated cookie is replaced.

For example, after a user signs out and another user signs in within the same browser, the frontend should obtain a fresh token.

A practical approach is to request a new token after authentication changes and when the API reports an antiforgery validation failure. Avoid blindly retrying every failed POST request because the original operation may have been processed in other failure scenarios.

Configure CORS for a Separate SPA and API

Many applications host the React frontend and ASP.NET Core API on different origins.

For example:

  • React frontend: https://app.example.com
  • ASP.NET Core API: https://api.example.com

If the application uses cookie-based authentication, the API must configure CORS to allow the trusted frontend origin and credentials.

builder.Services.AddCors(options =>
{
    options.AddPolicy("SpaPolicy", policy =>
    {
        policy
            .WithOrigins("https://app.example.com")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials();
    });
});

Add the CORS middleware to the request pipeline:

app.UseRouting();

app.UseCors("SpaPolicy");

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

The order matters because CORS processing must occur in the appropriate position in the middleware pipeline.

Do not combine AllowCredentials() with AllowAnyOrigin(). Browsers reject credentialed CORS responses that use a wildcard origin. Specify the trusted frontend origins explicitly.

Also remember that CORS and antiforgery protection solve different problems. CORS controls which browser origins can read cross-origin responses and, for preflighted requests, whether the browser proceeds with the actual request. It is not a replacement for antiforgery validation.

If the frontend and API are on different sites rather than merely different subdomains, cookie settings become more important. Cross-site cookie authentication generally requires SameSite=None and Secure, and the browser may apply additional third-party cookie restrictions.

Antiforgery Tokens vs Bearer Token Authentication

Not every SPA requires antiforgery tokens.

The authentication mechanism determines whether the application is exposed to the traditional CSRF threat.

Authentication approach CSRF risk Typical protection
Cookie-based authentication Yes Antiforgery tokens and appropriate cookie settings
Session-based authentication Yes Antiforgery tokens
Bearer token explicitly added to the Authorization header Generally not vulnerable to traditional cookie-based CSRF Protect tokens against theft and XSS
Authentication token stored in a cookie Yes Antiforgery protection
Mixed cookie and bearer authentication Depends on which credential authenticates the endpoint Review each endpoint’s authentication behavior

When a SPA stores an access token and explicitly adds it to the Authorization: Bearer header, the browser does not automatically attach that header to requests initiated by another website. This reduces the traditional CSRF risk.

However, storing bearer tokens in local storage introduces another security concern: malicious JavaScript running through an XSS vulnerability may read the token.

Antiforgery protection and XSS protection address different threats. An antiforgery token does not prevent malicious scripts from running in the trusted application.

Choose the authentication approach based on the application’s security requirements. Do not add antiforgery tokens mechanically to every bearer-token API without understanding how its credentials are sent.

Common Antiforgery Configuration Mistakes

Mistake Why it causes problems Recommended approach
Generating a token but not validating it The API accepts requests without checking the token Apply validation to state-changing endpoints
Using different header names The API cannot find the request token Keep frontend and backend header names consistent
Using AddControllers without a validation filter MVC antiforgery validation is not enabled automatically Register the appropriate global filter
Assuming CORS protects against CSRF CORS does not replace token validation Use antiforgery protection for cookie-authenticated operations
Using wildcard CORS with credentials Browsers reject the credentialed response Specify trusted origins
Setting SameSite=None without Secure Modern browsers reject the cookie Use HTTPS and configure both attributes
Caching the token response A stale response may be reused Return Cache-Control: no-store
Reusing a token after changing users The token may no longer match the authentication context Request a fresh token after authentication changes
Treating antiforgery tokens as authentication A valid token does not prove user identity or permissions Keep authentication and authorization checks

Additional Security Best Practices

Antiforgery tokens are an important part of browser security, but they should be combined with other protections.

Use HTTPS everywhere

Use HTTPS for the frontend, API, authentication endpoints, and token-generation endpoint. Secure cookies should not be transmitted over unencrypted connections.

Configure SameSite cookies carefully

The SameSite attribute helps control whether cookies are sent with cross-site requests.

Strict provides stronger restrictions but may affect legitimate navigation flows. Lax is often a practical default for browser authentication. None is needed for some cross-site authentication scenarios and must be combined with Secure.

Choose the setting based on the actual application architecture rather than copying a configuration without testing it.

Protect against XSS

An attacker who can execute JavaScript in the trusted application origin may be able to obtain an antiforgery request token and submit authenticated requests.

Use output encoding, validate untrusted input, avoid unsafe DOM operations, and deploy a suitable Content Security Policy.

Do not treat antiforgery tokens as a solution to cross-site scripting.

Never use GET for state-changing operations

GET requests should retrieve information rather than create, update, or delete resources.

A state-changing GET endpoint can be triggered through links, images, or other browser mechanisms. Antiforgery filters that exclude safe HTTP methods will not protect an endpoint that incorrectly changes data through GET.

Use POST, PUT, PATCH, or DELETE for operations that modify application state.

Review authentication and authorization separately

Antiforgery validation confirms that a request includes the expected token pair. It does not determine whether the authenticated user is allowed to update a particular resource.

Every protected endpoint must continue to enforce authorization rules.

Troubleshooting Antiforgery Errors

Antiforgery failures often appear as HTTP 400 responses. The request may be missing a token, may contain an invalid token, or may use a cookie that no longer matches the request token.

Check the following areas when troubleshooting:

  1. Confirm that the token-generation endpoint returns a request token.
  2. Verify that the browser receives the antiforgery cookie.
  3. Check that the frontend sends the request token in the configured header.
  4. Confirm that the header name matches the ASP.NET Core configuration.
  5. Verify that the authentication cookie and antiforgery cookie are sent with the request.
  6. Check the cookie’s domain, path, Secure, and SameSite attributes.
  7. Confirm that the CORS policy allows the frontend origin and credentials.
  8. Request a fresh token after signing in, signing out, or switching accounts.
  9. Check server logs for antiforgery validation exceptions without logging token values.

For cross-origin deployments, inspect the browser’s network tools to determine whether the browser sends the cookies and whether the preflight request succeeds.

Avoid logging complete antiforgery tokens or authentication cookies while debugging. These values should be treated as sensitive security material.

Advantages and Disadvantages of ASP.NET Core Antiforgery

Advantages Disadvantages
Built-in support in ASP.NET Core Requires frontend integration for SPAs
Protects cookie-authenticated state-changing requests Adds token-generation and validation steps
Supports MVC controllers and Razor-based applications Cross-origin cookie configuration can be complex
Uses a separate request token and cookie token Tokens may need refreshing after authentication changes
Can be configured with custom headers Does not protect against XSS
Works alongside authentication and authorization Requires testing across browsers and deployment environments

Conclusion

Single-page applications provide a responsive user experience, but their authentication design must account for browser security threats. When an ASP.NET Core application uses cookies to authenticate API requests, it should protect state-changing operations against Cross-Site Request Forgery.

ASP.NET Core provides built-in antiforgery services through IAntiforgery, AddAntiforgery, and validation filters. A SPA can request a token from the backend and include it in a custom header with subsequent requests. The API then validates the token pair before processing the operation.

For production applications, combine antiforgery validation with HTTPS, appropriate SameSite cookie settings, a strict CORS allowlist, authorization checks, and XSS protection.

The most important design decision is to understand how authentication credentials reach the API. Cookie-authenticated requests need CSRF protection, while bearer tokens explicitly attached through an authorization header have a different threat model. Applying the correct protection to each authentication flow helps build secure and reliable ASP.NET Core applications.

Best and Most Recommended ASP.NET Core 11.0 Hosting

Fortunately, there are a number of dependable and recommended web hosts available that can help you gain control of your website’s performance and improve your ASP.NET Core 11 web ranking. HostForLIFE.eu is highly recommended. In Europe, HostForLIFE.eu is the most popular option for first-time web hosts searching for an affordable plan. Their standard price begins at only €3.49 per month. Customers are permitted to choose quarterly and annual plans based on their preferences. HostForLIFE.eu guarantees “No Hidden Fees” and an industry-leading ’30 Days Cash Back’ policy. Customers who terminate their service within the first thirty days are eligible for a full refund.

By providing reseller hosting accounts, HostForLIFE.eu also gives its consumers the chance to generate income. You can purchase their reseller hosting account, host an unlimited number of websites on it, and even sell some of your hosting space to others. This is one of the most effective methods for making money online. They will take care of all your customers’ hosting needs, so you do not need to fret about hosting-related matters.