Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding AntiForgeryToken to non-Ajax Form Submit

I found plenty of examples that demonstrate how to add an AntiForgeryToken to the Ajax call for POST submit method. My need, as the title suggests, is to submit a form NOT via the ajax call. Instead, I'm simply using jQuery submit() function.

What I have in my razor view file is as follows (Note: I'm using html string literal because this particular DOM needs to be dynamically attached to a separate element at a later point):

var html =
    "<form id='exportPdfForm' action='" + exportUrl + "' method='post'>" +
        "<input type='hidden' id='exportContent'>" +
        "<input type='hidden' id='__RequestVerificationToken' value='@Html.AntiForgeryToken()'>" +
    "</form>";

And, obviously, I'm using the following jQuery to submit this form:

$("#exportPdfForm").submit();

Also, using the DOM Explorer I can see the AntiForgeryToken value is properly in place: enter image description here

However, when I actually submit the form, I still run into the The required anti-forgery form field "__RequestVerificationToken" is not present error. I checked out several other Q&A's but can't seem to find anything that might shed some light on my problem.

Am I missing something obvious or doing something wrong here?

EDIT (Solution)

Assigning the __RequestVerificationToken to the name attribute will fix it:

<input type='hidden' name='__RequestVerificationToken' value='...'>
like image 712
BinaryCat Avatar asked Sep 30 '22 05:09

BinaryCat


1 Answers

This one turns out to be one of those "How did I miss that...?!" moments. While the above approach is perfectly legitimate, the only problem is that the __RequestVerificationToken has to belong to a name attribute instead of to an id as in my initial example. I tried posting my form with the fix and the problem is now gone.

Obviously this wouldn't have been an issue in the first place if I could just use the <% Html.AntiForgeryToken(); %> expression, but this particular case required an unconventional approach for the reason I stated in my initial post. So, I guess this is something to look out for!

like image 145
BinaryCat Avatar answered Oct 05 '22 06:10

BinaryCat