今天完成Spring Security的时候出现了一个bug

一开始以为仅仅只是小问题。
Spring Security默认对不安全的HTTP方法(如POST请求)提供CSRF攻击保护
我找了好久才找到
https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#csrf-components
所有http请求都被会CsrfFilter拦截,CsrfBeanDefinitionParser中有一个私有类DefaultRequiresCsrfMatcher,如下图,只有GET、HEAD、TRACE、OPTIONS这4类方法会被放行。

解决方法,比较完善可以参考
https://www.cnblogs.com/yjmyzz/p/customize-CsrfFilter-to-ignore-certain-post-http-request.html
不过上面的做法太麻烦了
官方给了很多基于不同场景的解决方法
最简单的就是直接禁用csrf
https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#disable-csrf
不过直接禁用肯定不安全,官方也不建议,如果实在需要post请求的话,使用ignoringAntMatchers排掉路径,会好的。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.ignoringAntMatchers("/user/**") // 使用 ignoringAntMatchers 来禁用 /api/** 路径的 CSRF 保护
.ignoringAntMatchers("/checkCode/**") // 使用 ignoringAntMatchers 来禁用 /api/** 路径的 CSRF 保护
.and()
.authorizeRequests()
.anyRequest().permitAll();//其它请求全部放行
}
当然,从设计层面来看,也不应该在认证服务里用POST请求
我一开始为了节省服务器资源,所以将认证服务和用户管理放到一个模块,微服务的话,直接将认证服务提取为一个新模块,就不用像上面那样禁用csrf。


