use*_*811 16 security spring 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>
Run Code Online (Sandbox Code Playgroud)
我收到错误HTTP 403:
在请求参数'_csrf'或标题'X-CSRF-TOKEN'上找到无效的CSRF令牌'null'
如果我使用此行,CSRF正在工作:
<form action="#" th:action="@{/fileUpload} + '?' + ${_csrf.parameterName} + '=' + ${_csrf.token}" method="post" enctype="multipart/form-data">
Run Code Online (Sandbox Code Playgroud)
但是如果我使用标题,我怎样才能实现工作CSRF?
gon*_*mas 20
在与这个问题斗争了一段时间后,我终于弄清楚为什么官方Spring文档中的代码不起作用...请注意以下内容:
<meta name="_csrf" content="${_csrf.token}" />
<meta name="_csrf_header" content="${_csrf.headerName}" />
Run Code Online (Sandbox Code Playgroud)
这是关于JSP的文档!由于我们使用的是Thymeleaf,您需要做的是使用th:content而不是content:
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
Run Code Online (Sandbox Code Playgroud)
现在它有效!
<!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}"/>
Run Code Online (Sandbox Code Playgroud)
和
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);
}
Run Code Online (Sandbox Code Playgroud)
});
解决了jquery ajax请求删除的问题.我使用Spring Boot,Security和bootstrap -table.
就我个人而言,使用与您相同的配置(Thymleaf、Spring MVC、Spring Sec),我只能在通过 ajax 上传时使用元 csrf,如果以标准方式提交则可以直接插入操作 URL。因此使用不同类型的表格:
例如
<form action="#" th:action="@{/fileUpload} + '?' + ${_csrf.parameterName} + '=' + ${_csrf.token}" method="post" enctype="multipart/form-data">
Run Code Online (Sandbox Code Playgroud)
标准提交
<form action="#" th:action="@{/fileUpload}" method="post" enctype="multipart/form-data">
Run Code Online (Sandbox Code Playgroud)
使用以下 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);
});
Run Code Online (Sandbox Code Playgroud)
通过 Ajax/jQuery 提交。
根据我最近的研究,两者之间似乎没有完全集成,需要稍作修改才能使代码正常工作。
| 归档时间: |
|
| 查看次数: |
9190 次 |
| 最近记录: |