onsdag 7 augusti 2013

Post Antiforgerytoken manually

When you use the helper @Html.AntiForgeryToken() in a view this is the actual HTML result:
<input name="__RequestVerificationToken" type="hidden" 
value="{ long cryptic code }">
This input field is normally inside your <form>-element which means it will be attached to the request if you submit that form.
The problem occurs when this input field is outside of your form or if you are not submitting a form. Have no fear, there is a solution for this. The attribute [ValidateAntiForgeryToken] tells the server to look for a key with the name: "__RequestVerificationToken". Let's give the server what it wants!
First, get that value!
var antiforgeytoken = $('input[name=__RequestVerificationToken]').val();
Second, attach it to your AJAX-request (I use jQuery)
$.ajax({
  url: 'something/something',
  type: 'POST',
  contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // Default
  data: { 'somekey': 'someval', 
          '__RequestVerificationToken', antiforgeytoken }
});
Now your server is happy, and you are too!
Update:
The content type is important because of how the MVC Binder validates the request. If you want to use another content type this solution How can i supply an AntiForgeryToken when posting JSON data using $.ajax? proposes to separate the antiforgery token and the postdata in two different parameters.

Inga kommentarer:

Skicka en kommentar