【发布时间】:2016-04-17 06:58:57
【问题描述】:
我正在使用带有 CSRF 的 Spring Security,但我的 javascript 中的一些 POST 调用出现问题。对于我的页面,我使用 Thymeleaf 和 HTML 5,对于对我的控制器的 Rest 调用,我使用 jQuery.ajax。 如果我像这样对我的表单使用 ajax 调用:
$(function() {
$("#saveCarButton").click(
function() {
var form = $("#addCarForm");
$.ajax({
type : "POST",
url : form.attr("action"),
data : form.serialize(),
// all right with rest call
success : function(data) {...}
//error during rest call
error : function(data) {
window.location.href = "/500";
}
});
});
});
一切正常,但是当我调用这个函数时:
jQuery.ajax({
url : 'upload',
type: 'POST',
contentType: false,
processData: false,
data:formData,
beforeSend:function(xhr) {
waitingModal.showPleaseWait();
},
success: function(data,status,xhr){...}
error: function(xhr,status,e){
}
}).complete(function() {
//add timeout because otherwise user could see a too fast waiting modal
setTimeout(function(){
waitingModal.hidePleaseWait();
}, 1000);
});
我收到错误 403。 也许使用 thymeleaf 的形式,它可以正常工作,但是对于第二种类型的请求,我必须添加 CSRF 令牌。 我试过了
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
在我的html页面中我添加了
!-- -->
<meta name="_csrf" th:content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
为什么它与表单一起工作? 使用表单时不需要添加任何内容吗? 使用浏览器的开发工具可以看到 _csrf 和 _csrf_header 是否有危险? 谢谢
【问题讨论】:
标签: jquery html spring csrf thymeleaf