ASP.NET Core pass antiforgerytoken in json post request body
Well, I have a form created with the form tagHelper. Therefore, it includes special anti-forgery hidden for the token.
and I am trying to send the 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"
});
for a controller action that looks like this:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Feedback([FromBody]FeedbackViewModel vm)
{
...
}
Thus, the post data includes the key for the antiforgery token, however the request still fails the antiforgeryvalidation and does not fail. If I remove the anti-corrosion check attribute from the controller than it works fine.
Why doesn't it validate the token inside the request body - is this by design, or is it some kind of problem?
+3
source to share
2 answers
You can pass "headers" as shown 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});
+1
source to share
you can try to implement as below.
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(); }
});
0
source to share