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

探讨SpringSecurity中CSRF机制与Thymeleaf页面渲染的交互问题,特别是在懒加载session与页面缓冲提交冲突时的解决方案。文章提供了一种在head标签中设置CSRF的保险方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录


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.youkuaiyun.com/starrrr2/article/details/50074445

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值