尝试使用Spring MVC和Thymeleaf进行React/Ajax调用

goo*_*fiw 2 javascript spring spring-mvc csrf thymeleaf

根据文档,我应该能够在头文件中包含CSRF令牌,用jquery抓取它们,并将它们包含在我的ajax调用的头文件中.

不幸的是,包括

<html class='default' xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  <head>
    <meta charset='UTF-8'/>
    <meta http-equiv='X-UA-Compatible' content='IE=Edge,chrome=1' />
    <meta name="_csrf" content="${_csrf.token}"/>
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
...
</html>
Run Code Online (Sandbox Code Playgroud)

输出:

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="_csrf" content="${_csrf.token}">
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}">
Run Code Online (Sandbox Code Playgroud)

而不是实际的令牌,所以没有什么可以抓住.

有没有人用这种方式处理ajax post/puts/deletes?

参考:http: //docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html

Man*_* Zi 5

你忘记了前缀"th".您的模板应如下所示:

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

和你的ajax电话:

var token = $('#_csrf').attr('content');
var header = $('#_csrf_header').attr('content');

$.ajax({
    type: "POST",
    url: url,
    beforeSend: function (xhr) {
        xhr.setRequestHeader(header, token);
    },
    success: function (data, textStatus, jqXHR) {
        alert(status);
    },
    error: function (request, status, error) {
        alert(status);
    }
});
Run Code Online (Sandbox Code Playgroud)