Edwardo S Edwardo S - 6 months ago 43
Ajax Question

How to add csrf token to ajax request

I have issues adding csrf to ajax request. I'm using thymeleaf on client side with spring-boot/spring security. Spring security wouldn't allow the request because csrf-token is missing. Here is my code for ajax

function bits(){
var xhttp = new XMLHttpRequest();
var selected = document.getElementById("product").value;
xhttp.onreadystatechange = function(){
if(xhttp.readyState==4 && xhttp.status==200){
var result= JSON.parse(xhttp.responseText)
var length = result.length;
for(i=0; i<length; i++){

console.log(result[k].spid);
}
}

};

xhttp.open("POST", "http://localhost:8080/bids?q="+selected, true);
xhttp.send();


}

Help will be appreciated

Answer

I modified @Prakash Hari Sharma's solution and had the following code that worked for me. Note, th: prefix if using Thymeleaf.

--Header section

<meta th:name="_csrf" th:content="${_csrf.token}"/>
<meta th:name="_csrf_header" th:content="${_csrf.headerName}"/>

Ajax script function

...
...
var token = $("meta[name='_csrf']").attr("content"); 
var header = $("meta[name='_csrf_header']").attr("content");
xhttp.open("POST", "http://localhost:8080/bids?q="+selected,  true);
xmlhttp.setRequestHeader(header, token);
xhttp.send();

Hope this helps someone too.