使用spring security後,如果使用的是thymeleaf,那麼form action會幫我們自動加上csrf 隱藏域,但是ajax提交就需要自己獲取了,在文檔中有提到。
Example 124. AJAX send CSRF Token
$(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);
});
});
csrfMeta tag
If you are using JSPs a simple way to write the CSRF token to the meta
tags is by leveraging the csrfMeta tag.
CsrfToken Request Attribute
If the other options for including the actual CSRF token in the request do not work, you can take advantage of the fact that the CsrfToken
is exposed as an HttpServletRequest
attribute named _csrf
. An example of doing this with a JSP is shown below:
Example 125. CSRF meta tag JSP
<html>
<head>
<meta name="_csrf" content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<!-- ... -->
</head>
<!-- ... -->
所以我們首先需要在layout中加入meta。
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
然後再ajax中獲取meta
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.ajax({
type: "POST",
url: "xxx",
beforeSend: function(xhr) {
xhr.setRequestHeader(header, token);
},
success: function(msg){
}
});