如何仅在测试中禁用Spring Boot 3的CSRF防护
在Spring Boot 3.1.2中仅在测试环境禁用CSRF防护的推荐方法
你基于Spring Boot 3.1.2开发的应用已启用CSRF防护,但测试时授权失败(测试用例返回406而非预期的400),希望仅在测试环境中禁用CSRF防护。当前安全配置如下:
@Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers(openUrls).permitAll() .anyRequest().hasAuthority(applicationRoleKey)) .oauth2ResourceServer(oauth -> oauth .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter()))); return http.build(); }
你提到已通过在测试中添加.with(csrf())临时解决问题,以下是更通用的测试环境禁用方案:
方法一:利用Profile创建测试专用安全配置
通过Spring的@Profile注解,创建仅在测试环境生效的Security配置,覆盖默认配置并禁用CSRF:
@Configuration @Profile("test") public class TestSecurityConfig { @Bean protected SecurityFilterChain testFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers(openUrls).permitAll() .anyRequest().hasAuthority(applicationRoleKey)) .oauth2ResourceServer(oauth -> oauth .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter()))) .csrf(csrf -> csrf.disable()); // 测试环境禁用CSRF return http.build(); } }
启动测试时,通过测试类的@ActiveProfiles("test")注解激活测试Profile即可。
方法二:在测试类中直接覆盖安全配置
如果仅需要在特定测试类中禁用CSRF,可以在测试类内部定义专属的Security配置:
@SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") public class PhotoControllerTest { @Autowired private MockMvc mockMvc; // 测试专用安全配置,仅当前测试类生效 @Configuration static class TestSecurityConfig { @Bean protected SecurityFilterChain testFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers(openUrls).permitAll() .anyRequest().hasAuthority("user=admin")) .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults())) .csrf(csrf -> csrf.disable()); return http.build(); } } @Test @WithMockUser(authorities = "user=admin") void asAdmin_canGetPhoto() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/photo")) .andExpect(status().isOk()); } }
关于临时方案的说明
你使用的.with(csrf())本质是给请求添加CSRF Token而非禁用防护,适合单个测试用例的临时适配。如果需要批量测试跳过CSRF验证,上述两种方法更高效。
内容的提问来源于stack exchange,提问作者jessica96
相关产品推荐
相关产品推荐

