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">
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With