使用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" th:content="${_csrf.token}"/>
	<meta name="_csrf_header" th: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);
    }
});

参考:
https://www.cnblogs.com/ismallboy/p/6785328.html
https://blog.csdn.net/starrrr2/article/details/50074445

猜你喜欢

转载自blog.csdn.net/LSylvie/article/details/82825285