springboot 與 SpringSecurity整合后,為了防御csrf攻擊,只有GET|OPTIONS|HEAD|TRACE|CONNECTION可以通過。
其他方法請求時,需要有token
解決方法:
1,支持post的方法:
1,如果使用freemarker模板
在form里添加<input type="hidden" name="${_csrf.parameterName}" value="_csrf.token">
2,使用ajax時
$.ajax({
url:"/manager",
type:"POST",
data:{
"${_csrf.parameterName}":"${_csrf.token}",
//其他的數據
}
})
2,支持delete,put的方法:
在支持post的基礎上,
$.ajax({
url:"/manager",
type:"POST",
data:{
"${_csrf.parameterName}":"${_csrf.token}",
_method:"DELETE", /添加了這個,在后端就可以使用delete方法接收請求了,實現restful
//其他的數據
}
})
二、當開啟CSRF后,原來以Get方式,調用/logout,退出登錄狀態的功能失效了,跳轉后報404錯誤。
1、查看源碼,發現框架方法里做了備注。大概意思就是開啟CSRF后,logout方法需要以post方式提交。或者調用logoutRequestMatcher方法,顯示設置/logout請求為GET方法
2、用logoutRequestMatcher設置logout為get請求來解決404報錯問題。POST方式比較簡單這里就不在贅述。當然,實際項目中,最好選擇以post方式退出系統。
http
.formLogin().loginPage("/user/login.do")
.defaultSuccessUrl("/free/list.do")//啟用FORM登錄
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout","GET"))
至此CSRF防止方案示例就講完了。在項目中,對於post請求都需要注意提交_csrf到服務端。希望對你有所幫助,歡迎留言交流。
