问题描述
在 Springboot 中使用 SpringSecurity 后会出现使用 POST 无法提交请求的问题,原因是因为 SpringSecurity 为了防止跨域请求伪造,于是拦截了 POST 请求,而使用 GET 请求则不会出现这种问题。于是百度了一下,总结出如下办法解决 POST 无法提交的问题
解决办法
1). 如果是使用表单提交,在表单中添加隐藏域即可。
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
2). 如果是使用Ajax提交。
html 页面
<head>
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
...
</head>
ajax 的 js 中添加如下代码
$(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);
});
});
3). 直接关闭防跨域攻击功能。(该方法暴力不推荐使用)
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}