Share via

How to apply CSRF defense for an Axios requests on a ASP .NET CORE application

Sruthi Vishnubhatla 0 Reputation points
2025-08-25T04:27:27.88+00:00

I am working on applying CSRF defense on my application, I have applied the defense on Ajax requests but when it comes to Axios it doesn't seem to be working as expected.

previously i was working on CSRF Defense for Ajax requests globally on my application and i added the following: In program.cs


options.Filters.Add(new AutoValidateAntiforgeryTokenAt

tribute());

added this to the AddControllersWithViews service and this service

builder.Services.AddAntiforgery(options =>
{
    options.HeaderName = "X-XSRF-TOKEN";
    options.Cookie.Name = "XSRF-TOKEN";
    options.Cookie.HttpOnly = false;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});

and created a new file and generating csrf token

@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery antiforgery
<meta name="csrf-token" content="@antiforgery.GetAndStoreTokens(Context).RequestToken"/>

and added headers to vulnerable ajax calls

<script>
   $(function () {
        // Gets the CSRF token value in the page header
       var token = $("meta\[name='csrf-token']").attr("content");
        // Sets default configuration for all jQuery AJAX requests
       $.ajaxSetup({
            // If the HTTP method is NOT safe the CSRF token os added to the request 
           beforeSend: function (xhr, settings) {
               if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
                   xhr.setRequestHeader("X-XSRF-TOKEN", token);
               }
           }
       });
   });
</script>

and i called these globally in the layout. But when i comes to Axiox calls, I am unable to go through with this code, it keeps giving me a "Bad Request" but with a csrf token and a cookie generated. What might I be missing in the Axios configuration to resolve the 'Bad Request' issue?

Developer technologies | ASP.NET Core | Other

1 answer

Sort by: Most helpful
  1. Anonymous
    2025-08-25T04:50:07.8333333+00:00

    Hello Sruthi Vishnubhatla,

    Looking at your setup, you have the CSRF defense configured correctly for the server side, but there are a couple of things that might be causing the 400 Bad Request with Axios specifically.

    First, make sure your Axios interceptor is running before any requests are made. I notice you're using DOMContentLoaded, but if you have any Axios calls that run before this event fires, they won't have the CSRF token.

    Also, check that your Axios requests are actually hitting the interceptor. You can add some debugging:

    document.addEventListener('DOMContentLoaded', () => {
      const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
      console.log('CSRF Token found:', csrfToken); // Debug line
      if (csrfToken) {
        axios.interceptors.request.use(config => {
          console.log('Interceptor running for:', config.method, config.url); // Debug line
          if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(config.method)) {
            config.headers['X-XSRF-TOKEN'] = csrfToken;
            console.log('CSRF token added to headers'); // Debug line
          }
          return config;
        }, error => Promise.reject(error));
      } else {
        console.warn("CSRF token not found in meta tag");
      }
    });
    

    Another thing to verify, make sure your Axios requests are actually using the interceptor. If you're creating new Axios instances or using different configurations, they might not pick up the global interceptor.

    Also, double-check that your server-side antiforgery configuration matches exactly what you're sending. The header name should be "X-XSRF-TOKEN" (which you have correct), and make sure the cookie name matches too.

    If you're still getting 400 errors, can you check the browser's network tab to see what headers are actually being sent with the request? That might give me a clue about what's missing.

    Hope this helps!

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.