如何将csrf标记添加到ajax请求

Edw*_*o S 10 ajax spring spring-security thymeleaf

我有问题将csrf添加到ajax请求.我在客户端使用百里香叶弹簧/弹簧安全.Spring安全性不允许该请求,因为缺少csrf-token.这是我的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();
Run Code Online (Sandbox Code Playgroud)

}

帮助将不胜感激

Edw*_*o S 11

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

- 头部分

<meta th:name="_csrf" th:content="${_csrf.token}"/>
<meta th:name="_csrf_header" th:content="${_csrf.headerName}"/>
Run Code Online (Sandbox Code Playgroud)

Ajax脚本功能

...
...
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);
xhttp.setRequestHeader(header, token);
xhttp.send();
Run Code Online (Sandbox Code Playgroud)

希望这也有助于某人.


Tom*_*zyk 5

将@标记添加到<head>元素后,作为@EdwardoS答案的补充:

胸腺

<meta th:name="_csrf" th:content="${_csrf.token}"/>
<meta th:name="_csrf_header" th:content="${_csrf.headerName}"/>
Run Code Online (Sandbox Code Playgroud)

JSP:

<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
Run Code Online (Sandbox Code Playgroud)

...然后您可以执行Spring文档中建议的操作,并在将来的所有ajax中包含以下内容csrf

$(function () {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function (e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
});
Run Code Online (Sandbox Code Playgroud)