Spring Boot全局禁用CSRF仅针对指定路径启用的配置方法
全局禁用CSRF,仅指定路径启用的Spring Security配置方案
嘿,这个需求确实有点反直觉——毕竟大部分场景都是全局开、个别路径关,但Spring Security完全支持反过来的配置!我给你两种方案,对应不同的Spring Security版本:
方案1:基于WebSecurityConfigurerAdapter(旧版,适合Spring Security <5.7)
你可以通过拆分配置类的方式,用优先级控制让特定路径走启用CSRF的配置,其余路径走全局禁用的配置:
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // 主配置:全局禁用CSRF,处理所有非指定路径的请求 @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/**").permitAll() // 这里根据你的实际权限需求调整,比如改成authenticated() .and() .csrf().disable(); // 全局关闭CSRF防护 } // 单独配置需要启用CSRF的路径,优先级高于主配置 @Configuration @Order(1) public static class CsrfProtectedPathsConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 仅匹配你需要启用CSRF的两个路径 .requestMatchers() .antMatchers("/api/sensitive/**", "/admin/action/**") // 替换成你的目标路径 .and() // 对这些路径启用CSRF .csrf().enable() .and() .authorizeRequests() .antMatchers("/api/sensitive/**", "/admin/action/**").permitAll(); // 权限配置按需调整 } } }
关键说明:
@Order(1)确保这个特定配置先被Spring Security加载,当请求匹配指定路径时,会优先使用这个配置(启用CSRF)- 主配置的
csrf().disable()会覆盖所有未被特定配置匹配的请求,实现全局禁用
方案2:基于SecurityFilterChain(新版,Spring Security 5.7+推荐)
如果你的项目用的是Spring Security 5.7及以上版本,官方已经弃用了WebSecurityConfigurerAdapter,推荐用SecurityFilterChain的方式配置,逻辑和上面一致,但写法更清晰:
@Configuration public class WebSecurityConfig { // 第一个过滤器链:仅处理需要CSRF防护的路径,优先级更高 @Bean @Order(1) public SecurityFilterChain csrfEnabledFilterChain(HttpSecurity http) throws Exception { http // 指定要匹配的路径 .securityMatcher("/api/sensitive/**", "/admin/action/**") // 启用CSRF .csrf(csrf -> csrf.enable()) // 权限配置按需调整 .authorizeHttpRequests(auth -> auth .anyRequest().permitAll() ); return http.build(); } // 第二个过滤器链:处理所有其他路径,全局禁用CSRF @Bean public SecurityFilterChain defaultFilterChain(HttpSecurity http) throws Exception { http // 全局禁用CSRF .csrf(csrf -> csrf.disable()) // 权限配置按需调整 .authorizeHttpRequests(auth -> auth .anyRequest().permitAll() ); return http.build(); } }
注意事项:
- 路径匹配要准确:用
antMatchers时注意通配符的用法,比如/path/**会匹配该路径下的所有子路径,/path仅匹配精确路径 - 权限配置:示例里的
permitAll()是为了简化,实际项目中要根据业务需求替换成authenticated()或其他权限规则 - 优先级:一定要给特定路径的配置设置更高的
@Order值(数值越小优先级越高),否则会被全局配置覆盖
内容的提问来源于stack exchange,提问作者lambad
相关产品推荐
相关产品推荐

