将CSRF放入Spring 4.0.3 + Spring Security 3.2.3 + Thymeleaf 2.1.2中的Headers中

时间:2014-05-05 16:30:29

标签: spring security csrf thymeleaf

我有以下代码:

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta name="_csrf" th:content="${_csrf.token}"/>
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
    <title>Fileupload Test</title>
</head>
<body>

<p th:text="${msg}"></p>

<form action="#" th:action="@{/fileUpload}" method="post" enctype="multipart/form-data">
    <input type="file" name="myFile"/>
    <input type="submit"/>
</form>

</body>
</html>

我收到错误HTTP 403:

  

无效的CSRF令牌&#39; null&#39;在请求参数&#39; _csrf&#39;上找到或标题&#39; X-CSRF-TOKEN&#39;

如果我使用此行代替CSRF:

<form action="#" th:action="@{/fileUpload} + '?' + ${_csrf.parameterName} + '=' + ${_csrf.token}" method="post" enctype="multipart/form-data">

但如果我使用标题,我怎样才能实现CSRF工作?

3 个答案:

答案 0 :(得分:18)

在与这个问题斗争了一段时间之后,我终于弄清楚为什么official Spring documentation中的代码不起作用......请注意以下几点:

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

这是关于JSP的文档!由于我们使用的是Thymeleaf,您需要做的是使用th:content代替content

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

现在有效!

答案 1 :(得分:7)

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head>
<meta name="_csrf" th:content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>

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);
    });

$.ajax({
url: url,
method: 'DELETE',
success: function(result) {
    $('#table').bootstrapTable('remove', {
        field: 'id',
        values: [row.id]
    });
},
    error:function(result) {
    console.log(result);
}

});

解决了jquery ajax请求删除的问题。我使用Spring Boot,Security和bootstrap -table。

答案 2 :(得分:3)

个人使用与您相同的配置(Thymleaf,Spring MVC,Spring Sec)我只能在通过ajax上传时使用meta csrf,并且如果以标准方式提交,则直接插入操作URL。 所以使用不同类型的表格:

e.g。

<form action="#" th:action="@{/fileUpload} + '?' + ${_csrf.parameterName} + '=' + ${_csrf.token}" method="post" enctype="multipart/form-data">

for standard submition

<form action="#" th:action="@{/fileUpload}" method="post" enctype="multipart/form-data">

使用以下javascript:

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);
        });

通过Ajax / jQuery提交。

根据我最近的研究,似乎并不是两者之间的干净整合,需要稍作修改才能使代码有效。