A set of technologies in .NET for building web applications and web services. Miscellaneous topics that do not fit into specific categories.
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!