3

I have a scenario where i dont need to send form data but some other data through ajax call. I have a form which contains html.AntiForgeryToken() .

This is what i tried.

var modid = $("#moduleList").val();
var data = {};
data.modid = modid;

var token = $('#frmmmenu input[name="__RequestVerificationToken"]').val();
data.__RequestVerificationToken = token;
//var dataWithToken = $.extend(data, token);
$.ajax({
    type: "POST",
    url: "Home/MainMenu",
    data: JSON.stringify(data),
    //contentType: "application/json; charset=utf-8",  // request data type
    dataType: "html",  // response data type
    success: function (msg) {

        $("#accordion").html(msg);
    },
    error: function (msg) {
        alert("Ajax Error");
    },
});

But i keep getting The required anti-forgery form field "__RequestVerificationToken" is not present. error.

Here is the Firebug Screen grab

enter image description here

Also My action method is decorated with ValidateAntiForgeryToken

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult MainMenu(int modid)
{
}

What is causing this ? Any Ideas ?

EDIT : This is a MVC5 Project.

Deb
  • 981
  • 13
  • 39
  • @RoryMcCrossan Same value as in firebug post. – Deb Mar 30 '16 at 13:08
  • Take a look at [this](http://stackoverflow.com/questions/14473597/include-antiforgerytoken-in-ajax-post-asp-net-mvc) answer. – kayess Mar 30 '16 at 14:49
  • 1
    The `ValidationAntiForgeryTokeAttribute` does not support the token coming from JSON. Kayess's answer does not encode the values as JSON, that answer uses Form Encoded value. – Erik Philips Mar 30 '16 at 16:41
  • @ErikPhilips Exactly ! In my case i was not serialising the form and creating the object from scratch. Old habit of sending JSON led to the error :( – Deb Mar 30 '16 at 16:52
  • I only use JSON, so I derived from the attribute and wrote my own. That standard URL encoding pretty much sucks unless you're doing very basic things. – Erik Philips Mar 30 '16 at 16:58
  • @ErikPhilips Have you posted your solution anywhere ? – Deb Mar 30 '16 at 17:01
  • Sorry I misspoke, I use headers to append the AFT. I can't post the specific code for this. But if you wanted to do it, first I would look at [ValidateAntiForgeryTokenAttribute](https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Mvc/ValidateAntiForgeryTokenAttribute.cs) build your own to pull the valies then call [AntiForgery.Validate()](https://msdn.microsoft.com/en-us/library/jj158363(v=vs.111).aspx). And for reference: [AntiForgeryWorker](https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.WebPages/Helpers/AntiXsrf/AntiForgeryWorker.cs). – Erik Philips Mar 30 '16 at 17:32

2 Answers2

1

Found the solution.

The culprit was

data: JSON.stringify(data),

Changed the above to

data: data,

Now Firebug shows

enter image description here

Hope somebody can post a solution with JSON as Url length is limited although it requires contentType application/x-www-form-urlencoded

Thank you all for your support.

Deb
  • 981
  • 13
  • 39
  • 2
    Current solution is fine: URL Length is limited, but you're NOT using the URL when you POST via jQuey AJAX. You may be using "url-encoded" content, but that just means it follows the same structure as URL encoding (as opposed to JSON, CSV or something else). It's still being included in the message body, not URL. – binderbound Feb 28 '17 at 08:17
  • @binderbound Thanks Never new that. – Deb Jun 17 '17 at 05:11
0

For me, I had to try every post out there before I made a solution that was working:

JS

var form = jQuery("#AuthForm");
form.children("input[name=provider]").val(source.SourceName);
form.children("input[name=returnUrl]").val(window.location.href);

$.ajax({
 url: form.attr('action'),
 data: form.serialize(),
 success: function (response) {
  console.log(response);
 }
});

Obviously the values(.val() statements) I'm filling in are specific to my case. Also, I am running this in an angular app.

CSHTML

<form id="AuthForm" action="@Url.Action("LinkExternalLogin","LoginInfo")" method="post">
 @Html.AntiForgeryToken()
 <input type="hidden" name="provider" value="" />
 <input type="submit" name="returnUrl" value="" />
</form>
Loufs
  • 1,596
  • 1
  • 14
  • 22