Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make ajax request with anti-forgery token in mvc

I have problem with below details from MVC project.

When I am trying to use jquery ajax request with loading panel like spinning gif (or even text), I am getting error, observed from fiddler that

The required anti-forgery form field "__RequestVerificationToken" is not present.

If I comment [ValidateAntiForgeryToken] attribute at POST action method and use loading panel it is working fine.I want to know why I am getting this error.

I have even used the query string serialized with

__RequestVerificationToken= $('input[name="__RequestVerificationToken"').val() 

still I am getting error

The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the <machineKey> configuration specifies explicit encryption and validation keys.

AutoGenerate cannot be used in a cluster

What should I use?

Here it updated question code

var token = $('input[name="__RequestVerificationToken"]').val(); $('#submitaddress').click(function subaddr(event) {     event.preventDefault();     event.stopPropagation();   //$('#addAddress').html('<img src="/img/animated-overlay.gif"> Sending...');    // $('#addAddress').blur();     //  $(this).bl     if ($('#Jobid').val()!="") {         $('#TransportJobId').val(parseInt($('#Jobid').val()));         $.ajax(               {                   url: '/TransportJobAddress/create',                   type: 'POST',                   data: "__RequestVerificationToken=" + token + "" + $('form[action="/TransportJobAddress/Create"]').serialize(),                   success: function poste(data, textStatus, jqXHR) { $('#addAddress').html(data); return false; },                   error: function err(jqXHR, textStatus, errorThrown) { alert('error at address :' + errorThrown); }               });     }     else {         var transportid = 2;         $.ajax({             url: '/TransportJob/create',             type: 'POST',             data: "__RequestVerificationToken=" + token + "" + $('form[action="/TransportJob/Create"]').serialize(),             success: function sfn(data, textStatus, jqXHR) {                 transportid = parseInt(data);                 $('#Jobid').val(data);                // alert('inserted id :' + data);                 $('#TransportJobId').val((transportid));                 $.ajax(          {               url: '/TransportJobAddress/create',              type: 'POST',              //beforeSend: function myintserver(xhr){                //        $('#addAddress').html('<div id="temp_load" style="text-align:center">please wait ...</div>');              //},               data: "__RequestVerificationToken=" + token + "" + $('form[action="/TransportJobAddress/Create"]').serialize(),              success: function poste(data, textStatus, jqXHR) {                  $('#addAddress').html(data);               },              error: function err(jqXHR, textStatus, errorThrown) {                  alert('error at address :' + errorThrown);              }           });             },             error: function myfunction(jqXHR, textStatus, errorThrown) {                 alert("error at transport :" + jqXHR.textStatus);             },             complete: function completefunc() {               //  alert('ajax completed all requests');                 return false;             }          });     } }); 

form tags

<form action="/TransportJob/Create" method="post"><input     name="__RequestVerificationToken" type="hidden"   value="ydYSei0_RfyBf619dQrhDwwoCM7OwWkJQQEMNvNdAkefiFfYvRQ0MJYYu0zkktNxlJk_y1ZJO9-yb-  COap8mqd0cvh8cDYYik4HJ0pZXTgE1" />    

TransportJob form tag 2 on same page

<form action="/TransportJobAddress/Create" method="post" novalidate="novalidate"><input name="__RequestVerificationToken" type="hidden"    value="Np2vUZJPk1TJlv846oPSU6hg4SjMHRcCk1CacaqZbpHOg8WbV4GZv06noRDl7F_iT9qQf3BIXo3n9wGW68sU mki7g3-ku_BSHBDN-g2aaKc1">  

like image 866
Ravi Hanok Avatar asked Nov 05 '13 12:11

Ravi Hanok


People also ask

What is HTML AntiForgeryToken () in MVC?

This is to prevent Cross-site request forgery in your MVC application. This is part of the OWASP Top 10 and it is vital in terms of web security. Using the @Html. AntiforgeryToken() method will generate a token per every request so then no one can forge a form post.

How is Ajax implemented in MVC?

The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features. To enable the unobtrusive AJAX support in the MVC application, open the Web.

How do I get an AntiForgeryToken?

If you use the AntiForgery. GetTokens API, this method will return the raw tokens instead of generating an HTML snippet. The parameters to this method are: oldCookieToken: If the request already contains an anti-CSRF cookie token, provide it here.

What is the use of ValidateAntiForgeryToken in MVC?

The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks. A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user.


2 Answers

Rather than manually adding it to each request, I usually do something like this:

var token = $('input[name="__RequestVerificationToken"]').val(); $.ajaxPrefilter(function (options, originalOptions) {   if (options.type.toUpperCase() == "POST") {     options.data = $.param($.extend(originalOptions.data, { __RequestVerificationToken: token }));   } }); 

This will automatically add your token to any ajax POST you do.

like image 101
Kippie Avatar answered Sep 21 '22 11:09

Kippie


Have you added your token to the header of the ajax call?

You need to add AntiForgeryToken in your message header in the ajax call:

var token = $('input[name="__RequestVerificationToken"]').val();  var headers = {};  headers['__RequestVerificationToken'] = token;  $.ajax({         url: ... some url,         headers: headers,         .... }); 

Try this in your code:

var token = $('input[name="__RequestVerificationToken"]').val(); var tokenadr = $('form[action="/TransportJobAddress/Create"] input[name="__RequestVerificationToken"]').val();   var headers = {}; var headersadr = {}; headers['__RequestVerificationToken'] = token; headersadr['__RequestVerificationToken'] = tokenadr;  $('#submitaddress').click(function subaddr(event) {     event.preventDefault();     event.stopPropagation();   //$('#addAddress').html('<img src="/img/animated-overlay.gif"> Sending...');    // $('#addAddress').blur();     //  $(this).bl     if ($('#Jobid').val()!="") {         $('#TransportJobId').val(parseInt($('#Jobid').val()));         $.ajax(               {                   url: '/TransportJobAddress/create',                   type: 'POST',                   headers:headersadr,                    data: "__RequestVerificationToken=" + token + "" + $('form[action="/TransportJobAddress/Create"]').serialize(),                   success: function poste(data, textStatus, jqXHR) { $('#addAddress').html(data); return false; },                   error: function err(jqXHR, textStatus, errorThrown) { alert('error at address :' + errorThrown); }               });     }     else {         var transportid = 2;         $.ajax({             url: '/TransportJob/create',             type: 'POST',             headers:headers,              data: $('form[action="/TransportJob/Create"]').serialize(),             success: function sfn(data, textStatus, jqXHR) {                 transportid = parseInt(data);                 $('#Jobid').val(data);                // alert('inserted id :' + data);                 $('#TransportJobId').val((transportid));                 $.ajax(          {               url: '/TransportJobAddress/create',              type: 'POST',              //beforeSend: function myintserver(xhr){                //        $('#addAddress').html('<div id="temp_load" style="text-align:center">please wait ...</div>');              //},              headers:headers,               data: $('form[action="/TransportJobAddress/Create"]').serialize(),              success: function poste(data, textStatus, jqXHR) {                  $('#addAddress').html(data);               },              error: function err(jqXHR, textStatus, errorThrown) {                  alert('error at address :' + errorThrown);              }           });             },             error: function myfunction(jqXHR, textStatus, errorThrown) {                 alert("error at transport :" + jqXHR.textStatus);             },             complete: function completefunc() {               //  alert('ajax completed all requests');                 return false;             }          });     } }); 

Added headers line in your ajax call.

like image 43
freshbm Avatar answered Sep 22 '22 11:09

freshbm