排查springsecurity,get请求正常,post请求403错误

本文所使用的springboot版本:2.7.6

引入springsecurity后,配置所有请求均可访问:

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    
    
        http.authorizeRequests().anyRequest().permitAll();
        return http.build();
    }
}

发送post请求时,响应403:

{
    
    
	"timestamp": "2023-08-03T06:56:00.277+00:00",
	"status": 403,
	"error": "Forbidden",
	"path": "/hi"
}

控制台没有相关错误提示,于是开启了debug,trace看看具体错误详情:

debug: true
trace: true

再次发起请求,控制台打印出了相关错误信息,是被CsrfFilter过滤器拦截了

o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://127.0.0.1:9001/hi
o.s.s.w.access.AccessDeniedHandlerImpl   : Responding with 403 status code
o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [{
    
    timestamp=Thu Aug 03 14:56:00 CST 2023, status=403, error=Forbidden, path=/hi}]

根据类路径:o.s.security.web.csrf.CsrfFilter,查看CsrfFilter代码,为了防止csrf攻击,CsrfFilter会校验请求携带的csrftoken正确性,不通过则响应403,部分关键代码:
在这里插入图片描述
在这里插入图片描述
所以表现为get请求正常,post请求出现403错误。

csrf属于沉睡的巨人,需要防护。不使用springsecurity csrftoken这一套的,将csrf禁用掉即可:

http.authorizeRequests().anyRequest().permitAll().and().csrf().disable();

猜你喜欢

转载自blog.csdn.net/weixin_43275277/article/details/132083862