背景
本系列教程,是作为团队内部的培训资料准备的。主要以实验的方式来体验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 further customizations
*/
public CsrfConfigure