Spring Boot项目出现Cross-Site Request Forgery(CSRF)错误如何解决
问题关联代码
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().httpBasic().authenticationEntryPoint(authEntryPointToken) .and().authorizeRequests().antMatchers("/**").permitAll().anyRequest().authenticated() .and().cors().and().csrf().disable();
解决方案
你配置了csrf().disable()仍然触发CSRF异常,可按以下步骤逐一排查解决:
- 确认配置类生效
你的Security配置类必须添加@Configuration、@EnableWebSecurity注解,且处于Spring组件扫描的包路径下,否则配置不会被加载,CSRF默认仍为开启状态。 - 排查多配置优先级冲突
如果项目中存在多个Security配置类(多个SecurityFilterChain实例/多个继承WebSecurityConfigurerAdapter的类),请确认优先级更高(@Order注解数值更小)的配置类也关闭了CSRF,高优先级配置未关闭CSRF的话,低优先级的配置不会生效。 - 修正路径匹配逻辑冲突
你现有配置的路径规则存在逻辑冲突:antMatchers("/**").permitAll().anyRequest().authenticated,/**已经匹配了所有路径,后续的anyRequest规则不会生效。如果你是针对特定路径前缀做安全控制,需要先指定配置的作用域,示例:// 仅对/api/**路径生效的配置 http.antMatcher("/api/**") .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().httpBasic().authenticationEntryPoint(authEntryPointToken) .and().authorizeRequests() .anyRequest().authenticated() .and().cors() .and().csrf().disable(); - 适配Spring Security版本的写法
如果你使用的是Spring Security 6+版本,旧的链式and()写法已被废弃,CSRF关闭需使用Lambda写法,示例:@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .httpBasic(basic -> basic.authenticationEntryPoint(authEntryPointToken)) .authorizeHttpRequests(auth -> auth.anyRequest().authenticated()) .cors(cors -> cors.configure(http)) .csrf(csrf -> csrf.disable()); return http.build(); } - 排查自定义CSRF校验逻辑
确认项目中没有自行实现的CSRF校验拦截器/过滤器,部分业务封装框架会自带CSRF校验逻辑,需单独关闭对应配置。
内容的提问来源于stack exchange,提问作者Dinesh
相关产品推荐
相关产品推荐

