Anti-forgery token validation failed : The required anti-forgery cookie RequestVerificationToken is not present

Hello everyone, In this blog we will see a common error that we can encountered whenever we are doing a form submission using Jquery.I encountered the below highlighted error when i was trying to submit a custom form in Sitecore SXA website.

Anti-forgery token validation failed : The required anti-forgery cookie "__RequestVerificationToken" is not present.

When you do a form serialize and submit the form, there is high chance that this issue will not come if you have included @Html.AntiForgeryToken() inside form tag. But when there is requirement to pass custom model instead of whole form, then we have to manually pass this token in our Jquery Ajax request.

I encountered similar scenario and faced the above issue. Checked many blogs but it didn't helped me. So thought of noting the solution which worked for me.But before that just checked, few important things listed below.

  • Check @Html.AntiForgeryToken() is included properly inside your form tag
  • Inspect your html and check __RequestVerificationToken input field is getting generated properly.

If above checks are proper, then it clearly confirms that, the way you are passing the __RequestVerificationToken is not correct. Many blogs suggested me to pass the value in request header but it didn' worked.

So the proper way of passing the __RequestVerificationToken is to pass that in rquest body. Below code snippet will helo you to understand the same.

       
       let requestverificationtoken = document.querySelector('input[name="__RequestVerificationToken"]');
       let Model = {
						"name" : "Test"
						"__RequestVerificationToken" : requestverificationtoken.value
					}
       $.ajax({
						url : '',
						type : 'POST',
						data: Model
					}).done(function(data){
                    	// do other process
                    })
                      .fail(function(error){
                       console.log('error',error.toString());
                    })
	   

Thank you for reading. Keep Learning and sharing

You can check my other blogs too if interested. Blog Website

Comments

Popular posts from this blog

Sitecore XM Cloud Form Integration with Azure Function as Webhook

Automate RSS Feed to Sitecore XM Cloud: Logic App, Next.js API & Authoring API Integration

Create and Fetch Content From Sitecore Content Hub One using GraphQL and React