Spring Boot 3.1.5升级后集成测试中禁用CSRF的问题
Spring Boot 3.1.5集成测试403问题排查与解决
问题分析
你的403错误大概率不是CSRF未禁用导致的,先看配置和测试代码里的几个关键问题:
- 授权规则顺序错误:Spring Security的请求匹配规则是从上到下优先匹配,你对
/api/v1/test先设置了.hasRole("xxx"),之后又设置.permitAll(),后者永远不会生效。这会导致访问该接口必须拥有xxx角色,但测试中未携带认证信息,直接触发403。 - 重复的CSRF禁用配置:你连续调用了两次CSRF禁用代码,属于冗余配置,建议只保留一处。
- 测试类注解缺失:如果用
@SpringBootTest做集成测试,需要额外添加@AutoConfigureMockMvc;如果用@WebMvcTest,要确保Security配置类被扫描到或手动导入。
修复步骤
1. 修正Security授权规则
调整/api/v1/test的匹配顺序,删除冗余规则(如果需求是允许所有访问的话):
@Configuration public class SecurityConfig { @Bean protected SecurityFilterChain configure(HttpSecurity http) throws Exception { http .addFilterBefore(new AuthFilter(), BasicAuthenticationFilter.class) .cors(cors -> cors.configurationSource(r -> config)) .csrf(csrf -> csrf.disable()) // 仅保留一处CSRF禁用 .headers(headers -> headers .frameOptions(frameOptions -> frameOptions.sameOrigin())) .authorizeRequests(auth -> auth .requestMatchers("/actuator/**").hasRole("ACTUATOR") .requestMatchers("/api/v1/test").permitAll() // 优先匹配允许所有访问 .anyRequest().denyAll() ).httpBasic(Customizer.withDefaults()); return http.build(); } }
2. 确保测试类配置正确
- 如果是集成测试(加载完整Spring上下文):
@SpringBootTest @AutoConfigureMockMvc // 必须添加该注解初始化MockMvc class YourIntegrationTest { @Autowired private MockMvc mockMvc; @Test void demo() throws Exception { mockMvc.perform(post("/api/v1/test") .contentType(MediaType.APPLICATION_JSON) .content(body)) .andExpect(status().isOk()); } }
- 如果是Web层测试(仅加载Web相关上下文):
@WebMvcTest(YourTestController.class) @Import(SecurityConfig.class) // 手动导入Security配置类 class YourWebMvcTest { @Autowired private MockMvc mockMvc; @Test void demo() throws Exception { mockMvc.perform(post("/api/v1/test") .contentType(MediaType.APPLICATION_JSON) .content(body)) .andExpect(status().isOk()); } }
3. 测试中强制禁用CSRF(可选)
如果配置层面的禁用仍未生效,可以在测试请求中直接关闭CSRF验证:
@Test void demo() throws Exception { mockMvc.perform(post("/api/v1/test") .contentType(MediaType.APPLICATION_JSON) .content(body) .with(csrf().disable())) // 测试请求中单独禁用CSRF .andExpect(status().isOk()); }
关键注意点
- Spring Boot 3.x已弃用
WebSecurityConfigurerAdapter,建议使用组件式配置(如上述SecurityFilterChainBean)。 - 检查自定义的
AuthFilter是否会拦截请求并返回403,这也可能是问题根源。
内容的提问来源于stack exchange,提问作者techqueries
相关产品推荐
相关产品推荐

