3

Well, I have a form rendered via form tagHelper. So it's include special hidden for anti-forgery token.

and I'm trying to send following ajax request:

var data = JSON.stringify(feedbackForm.serializeArray().reduce((res, item) => {
       res[item.name] = item.value;
       return res; }, {}));
 // data example: '{"Description":"some description", "__RequestVerificationToken":"CfDJ8F9f8kTKlVNEsnTxejQIJ__pRCl2CuZTQDVAY2216J7GgHWGDC0XUMPc0FKHpr_K5uhz8Kx0VeHDkIPdQ3V0Xur9oLE2u_bpfXuVss6AWX3BVh0WbwfQriaibOrf_yvEuIYZV-jHU_G-AHPD91cKz_QE7MVmeLVgTum80yTb8biGctMtJcU67Wp7ZgN86yMuew"}'` 
  $.ajax({
         type: "POST",
         url: '@Url.Action("Feedback", "Profile", new {Area = ""})',
         contentType: "application/json; charset=utf-8",
         data: data,
         dataType: "json"
  });

to controller action which looks like that:

 [HttpPost]
 [AllowAnonymous]
 [ValidateAntiForgeryToken]
 public async Task<IActionResult> Feedback([FromBody]FeedbackViewModel vm)
 {
    ...
 }

So post data include key for antiforgery token, however request still not pass antiforgeryvalidation and failed with error. If I remove antiforgery validation attribute from controller than it works perfectly.

Why it not check token inside request body - is it by design, or it's some kind of an issue?

silent_coder
  • 5,370
  • 10
  • 39
  • 82
  • Possible duplicate of [Enable Antiforgery Token with ASP.NET Core and JQuery](https://stackoverflow.com/questions/40530474/enable-antiforgery-token-with-asp-net-core-and-jquery) – Andrew Grothe Jun 19 '17 at 16:15
  • Well, I don't want to change implementation into headers, I want to find out why it's not work with request body. – silent_coder Jun 19 '17 at 16:16
  • I've been doing similar work lately and IIRC, you need the header and the data element to match. – Andrew Grothe Jun 19 '17 at 16:20
  • @silent_coder I believe you are looking for [this](https://stackoverflow.com/questions/2906754/how-can-i-supply-an-antiforgerytoken-when-posting-json-data-using-ajax) – johnny 5 Jun 19 '17 at 16:30
  • I dont have the time to fully verify it, but _I think_ it cannot verify the token when you send data as a json ("application/json") the CSRF middleware cannot deserialize the json and get the token from there. It could however if your ajax post sends the data as a url encoded form ("application/x-www-form-urlencoded") which is essentially the same as a regular post. Thats why in the json case you need to add the token as a header – Daniel J.G. Jun 19 '17 at 21:10
  • @silent_coder did you solve the problem? – hasan Jun 26 '17 at 12:39
  • I refer you to a comprehensive source through following link [include antiforgerytoken in ajax post ASP.NET MVC](https://stackoverflow.com/questions/14473597/include-antiforgerytoken-in-ajax-post-asp-net-mvc/35556245#35556245) – Abolfazl Sep 23 '19 at 15:14

2 Answers2

0

can you try to implement like following.

data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
var data = JSON.stringify(feedbackForm.serializeArray().reduce((res, item) => {
   res[item.name] = item.value;
   return res; }, {}));

$.ajax({
    url: '@Url.Action("Feedback", "Profile", new {Area = ""})',
    contentType: "application/json"
    type: 'POST',
    context: document.body,
    data: data,
    success: function() { refresh(); }
});
hasan
  • 3,257
  • 1
  • 13
  • 21
0

You can pass "headers" like below.

var data = JSON.stringify(feedbackForm.serializeArray().reduce((res, item) => {res[item.name] = item.value;return res; }, {}));
$.ajax({
     url: '@Url.Action("Feedback", "Profile", new {Area = ""})',
     type: "POST",
     dataType: "json",
     headers: {"__RequestVerificationToken":$('[name=__RequestVerificationToken]').val()},         
     contentType: "application/json; charset=utf-8",
     data: data});

Refer:https://api.jquery.com/jQuery.ajax/

Sarthak Gupta
  • 195
  • 1
  • 13
  • Welcome to StackOverflow! Please edit your answer to include an explanation for your code, and how it differs from the other solutions. This will make it more likely that your answer will be found useful and upvoted :) – Das_Geek Sep 23 '19 at 14:52