The razor pages in ASP.NET Core have a feature that automatically protects the form from cross-site forgery (CSRF/XSRF) attacks using the FormHelperTag. Writing no extra code it will auto create an anti-forgery token. So, it will fail any AJAX request, if it does not have an anti-forgery token header.
This article explains, how to configure and how to send an AJAX request with an anti-forgery token header. Let us see it in four steps.
Step 1: Set Antiforgery Option
Customize the Anti-forgery option in Startup configure service. To that, add the below configuration code in the Startup.cs before the services. AddMvc().
The header name “XSRF-TOKEN” would be used to refer in the AJAX call. When the request is sent through AJAX script, the configuration service will check for the header “XSRF-TOKEN”.
Step 2: Design a form
I have added a button element inside the form element. The FormTagHelper will create a request verification token. For more details on FormTagHelper, check this article
Step 3: Validate anti-forgery token in Controller
I have added the [ValidateAntiForgeryToken] attribute in the OnPost() action, to validate the anti-forgery token. This attribute will prevent the cross-site request forgery.
Step 4: AJAX request
The following code snippet illustrates the AJAX call. I have passed the AJAX request in the button click event. In the beforeSend function, setRequestHeader() to set the HTTP header with the XSRF-TOKEN. It sends the __RequestVerificationToken.
When the user clicks the button, it will display the alert message ‘AJAX Response’
The following is a screenshot of the developer tool. The RequestVerificationToken has generated automatically with the alphanumeric value by FormTagHelper. The second image shows the request header of the AJAX request. The AJAX request passes the same RequestVerificationToken value in the input element. Then the server will validate the token and will grant the response.
This article explains AJAX call back in ASP.NET CORE razor page.
If you have questions, please leave a comment.