如何将csrf令牌添加到ajax请求中

我在向ajax请求添加csrf时遇到问题。我在客户端使用thymeleaf和springboot/springsecurity。Spring security不允许该请求,因为缺少csrf令牌。这是我的ajax代码

功能位(){
var xhttp=newXMLHttpRequest();
所选变量=document.getElementById(“产品”).value;
xhttp.onreadystatechange=函数(){
如果(xhttp.readyState==4&xhttp.status==200){
var result=JSON.parse(xhttp.responseText)
变量长度=result.length;
对于(i=0;i<长度;i++){
console.log(结果[k].spid);
}
}
};
xhttp.open(“POST”http://localhost:8080/bids?q=“+选中,为真);
xhttp.send();

}

我们将不胜感激

我修改了@Prakash Hari Sharma的解决方案,并使用了以下代码。注意,th:如果使用Thymeleaf,则为前缀

–标题部分

<meta-th:name=“\u-csrf”th:content=“${\u-csrf.token}”/>
<meta-th:name=“\u-csrf\u-header”th:content=“${u-csrf.headerName}”/>

Ajax脚本函数

。。。
...
var token=$(“meta[name=''u csrf']”)attr(“content”);
var header=$(“meta[name=''u csrf_header']”)attr(“content”);
...
...
xhttp.open(“POST”http://localhost:8080/bids?q=“+选中,为真);
setRequestHeader(头,令牌);
xhttp.send();

希望这对别人也有帮助

发表评论