1. 程式人生 > >使用thymeleaf+spring security處理csrf時遇到Cannot create a session after the response has been committed

使用thymeleaf+spring security處理csrf時遇到Cannot create a session after the response has been committed

文章目錄

被這個問題折磨了幾個小時,期間懷疑了各種程式碼,但最終還是讓我發現了根本性的原因

spring security中預設csrf是懶載入的,只有在第一次使用_csrf時才會建立session

而thymeleaf頁面的緩衝區滿後,response會在模板渲染完畢前被提交,所以response已提交時,若在剩餘的模板程式碼中使用了_csrf並且之前還沒建立過session,就會報錯

還是用head的方式保險

<head>
	<meta name="_csrf" content="${_csrf.token}"/>
	<meta name="_csrf_header"
content="${_csrf.headerName}"/>
</head>
var header = $("meta[name='_csrf_header']").attr("content");
var token = $("meta[name='_csrf']").attr("content");
 
$.ajax({
    url: '/test',
    type: 'POST',
    beforeSend: function(xhr){
        xhr.setRequestHeader(header, token);
    },
    success:
function(data) { console.log(data); }, error: function (xhr, ajaxOptions, thrownError) { console.log(xhr.status + ": " + thrownError); } });