背景
本系列教程,是作为团队内部的培训资料准备的。主要以实验的方式来体验SpringSecurity的各项Feature。
实验0:SpringSecurity默认开启CSRF防护
现在我们在springboot-security项目的HelloController.java中新增一个POST接口:/ok。
@RestController
public class HelloController {@GetMapping("/hello")public String hello(){return "hello springsecurity";}@PostMapping("/ok")public String ok(){return "ok";}
}
当然这个POST接口无法直接在浏览器中发起请求,我们需要借助PostMan来实现POST请求的发送。把浏览器中的Cookie复制到PostMan中。
- 先发GET /hello,正常
- 再发POST /ok,403了。。
那么,问题来了,两个请求都是在登录状态下进行的,为什么GET成功,POST返回403了?
其实SpringSecurity默认就开启了CSRF防护,这在上一篇及官网中关于SpringBoot自动配置项那里可以看到。并且SpringSecurity默认忽略"GET", “HEAD”, “TRACE”, "OPTIONS"等请求,源码如下:
/**
* Specify the {@link RequestMatcher} to use for determining when CSRF should be
* applied. The default is to ignore GET, HEAD, TRACE, OPTIONS and process all other
* requests.
*
* @param requireCsrfProtectionMatcher the {@link RequestMatcher} to use
* @return the {@link CsrfConfigurer} for furt

本文通过实验介绍了SpringSecurity默认的CSRF防护机制,展示了GET请求为何能通过而POST请求被拦截。实验涉及不同域名下的请求,以及CSRF在GET和POST请求中的表现,强调了POST请求的安全性。最后提出了开启CSRF防护后,前端如何发起POST请求以及何时需要CSRF防护的问题。
最低0.47元/天 解锁文章
701

被折叠的 条评论
为什么被折叠?



