MVC Core [ValidateAntiForgeryToken] for Ajax POST request

 Author: Shengtao Zhou       Created: 1/10/2019 11:46:38 PM       Modified: 2/2/2019 5:33:00 AM   More...

For ajax request, you need to explicitly send Verification token to the controller action that decorated with [ValidateAntiForgeryToken] attribute.


1. Make sure have the form tag defined in your view, this will generate the HTML components for the token

<form asp-action="AddComment">

2. Add beforeSend event for your ajax call, and send the token with your request header

$.ajax({
         type: 'POST',
         url: '/Posts/AddComment',
         data: JSON.stringify(comment),
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         beforeSend: function (xhr) {
                  xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
},


3. Add following code to ConfigureServices(IServiceCollection services) method in Startup.cs

services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

4. Add [ValidateAntiForgeryToken] attribute to the top of your HttpPost controller action

This is a good article "Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core"
https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-2.2


More...          Back to List          

(Please enter you comments between 100 to 2000 characters. Thanks for your contribution.) 

         Created:       Modified: 

Editing a comment

       (Please enter you comments between 100 to 2000 characters. Please login before edit comment.) 

div class="col-md-2">