Loading... ## 0x01 最近在写个前后端分离的程序,但是用上Spring Security框架后发现除了Get请求外,Post等请求会返回403,首先403错误,表示资源不可用,也就是服务器理解客户端的请求,但拒绝处理它(说人话就是我知道你要干什么,但是我不想理你.jpg)。  ## 0x02 在面向搜索引擎编程后了解到是由于Spring Security默认开启了防CSRF(跨站点请求伪造) 翻阅了下官方文档找到下面这段话 > Safe Methods Must be Idempotent In order for either protection against CSRF to work, the application must ensure that "safe" HTTP methods are idempotent. This means that requests with the HTTP method GET, HEAD, OPTIONS, and TRACE should not change the state of the application. 也就是说安全方法必须是幂等的,而Get方法用于获取资源,不会对程序本身产生影响,所以是幂等的,这也就是为什么Get请求能够正常通过,而Post等请求会返回403 ## 0x03 了解到原因后就是解决办法了 官方给出了两种方案,一种是禁用CSRF,但是并不推荐这么做,关闭CSRF会给网站带来一定被攻击的风险,另一种方式则是请求时带上csrftoken,因为这个程序是自己用的,所以怎么方便怎么来 (被打 *禁用CSRF* ```java http.csrf().disable().authorizeRequests(); ``` > Synchronizer Token Pattern The predominant and most comprehensive way to protect against CSRF attacks is to use the Synchronizer Token Pattern. This solution is to ensure that each HTTP request requires, in addition to our session cookie, a secure random generated value called a CSRF token must be present in the HTTP request. > When an HTTP request is submitted, the server must look up the expected CSRF token and compare it against the actual CSRF token in the HTTP request. If the values do not match, the HTTP request should be rejected. 根据以上文档描述可以了解到,如果需要使用CSRF,那么必须在请求中包含一个随机生成的值,这就是CSRF Token。 提交请求时,服务端会比对请求中的CSRF Token,如果不匹配,则会拒绝请求。 *请求时带上CSRF Token* ```yaml POST /transfer HTTP/1.1 Host: bank.example.com Cookie: JSESSIONID=randomid Content-Type: application/x-www-form-urlencoded amount=100.00&routingNumber=1234&account=9876&_csrf=4bfd1575-3ad1-4d21-96c7-4ef2d9f86721 ``` 最后修改:2020 年 09 月 16 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 0 如果觉得我的文章对你有用,请随意赞赏
7 条评论
文章写得很好
感觉Spring Security配置起来真的特别麻烦,真的没有shiro简单方便
Shiro确实更方便一些
老哥诈尸更新,我今天也诈尸了, OωO
最近忙事太多了,忙  ̄﹃ ̄
真诈尸了!! ::(啊)
∠( ᐛ 」∠)_ 是啊