ASP.NET Core MVC Interview Question #159

How should anti-forgery protection be handled with JavaScript POST requests?

Testing, AJAX/JavaScript Integration, Localization & Advanced MVC Senior Advanced

Quick Interview Answer

A state-changing request authenticated by browser cookies remains exposed to CSRF even when it is sent through JavaScript. The request should provide the anti-forgery token expected by the server, commonly by reading a generated token from the page and sending it in a form value or configured request header.

Detailed Explanation

A state-changing request authenticated by browser cookies remains exposed to CSRF even when it is sent through JavaScript. The request should provide the anti-forgery token expected by the server, commonly by reading a generated token from the page and sending it in a form value or configured request header.

The server action must validate the token. The exact JavaScript approach depends on whether the request uses FormData, URL-encoded data, JSON, and the application's anti-forgery configuration.

Code Example

const token = document.querySelector(
    'input[name="__RequestVerificationToken"]').value;

await fetch('/Products/Delete/10', {
    method: 'POST',
    headers: {
        'RequestVerificationToken': token
    }
});