Javascript 尝试使用springmvc和Thymeleaf的React/Ajax调用
根据文档,我应该能够将CSRF令牌包含在标题中,使用jquery获取它们,并将它们包含在ajax调用的标题中 不幸的是,包括Javascript 尝试使用springmvc和Thymeleaf的React/Ajax调用,javascript,spring,spring-mvc,csrf,thymeleaf,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-Compat
<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>
...
产出:
<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}">
而且不是真正的代币,所以没有什么可抢的
有人用这种方法处理ajax post/puts/deletes成功吗
参考:
以下是我如何制作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);
}
}
我还使用ajaxForm插件提交表单,在这种情况下,我将csrf嵌入到动作url中
希望对你有用。你忘了前缀“th”。您的模板应如下所示:
<meta id="_csrf" name="_csrf" th:content="${_csrf.token}"/>
<meta id="_csrf_header" name="_csrf_header" th:content="${_csrf.headerName}"/>
你看到这个了吗?_csrf代币没有通过。这很有效,如果他们在文档中有这样的代币就好了。我忘了索引在根目录下,所以我不会抱怨名称空间!你救了我的命!万分感谢
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);
}
});