使用 @Bean SecurityFilterChain 禁用所有静态资源安全拦截

解读

在国内一线互联网公司的 Spring Boot 面试中,这道题表面问“如何放行静态资源”,实则考察候选人是否真正理解 Spring Security 5.4+ 的过滤器链架构、RequestMatcher 的匹配顺序 以及 Spring Boot 默认静态资源映射规则。
很多候选人直接回答 .antMatchers("/static/**").permitAll(),结果一追问就暴露三个致命缺陷:

  1. 不知道 Spring Boot 默认把 /css/**、/js/**、/images/** 等目录直接映射到 classpath:/static/ 根路径,路径匹配写错导致 403 依旧;
  2. 不了解 SecurityFilterChain 的 “首次匹配即返回” 原则,把放行规则写在 .anyRequest().authenticated() 之后,顺序错误导致规则失效;
  3. 不清楚 Spring Security 6.x 已彻底废弃 WebSecurityCustomizer,如果再用 web.ignoring() 会被直接判为过时方案,直接扣分。
    因此,答案必须同时给出正确路径、正确顺序、正确写法,并解释为何不能用旧 API。

知识点

  1. Spring Boot 默认静态资源映射:
    classpath:/META-INF/resources/ > classpath:/resources/ > classpath:/static/ > classpath:/public/;
    访问时不带 /static 前缀,例如 http://host/css/app.css 对应 classpath:/static/css/app.css。
  2. SecurityFilterChain 的匹配顺序:先声明优先,一旦命中立即返回,不再执行后续规则。
  3. Spring Security 5.4+ 推荐纯 Java 配置,禁用 WebSecurityConfigurerAdapter;Spring Security 6.x 直接移除该适配器,只能使用 SecurityFilterChain Bean。
  4. 静态资源放行两种手段:
    • 在 HttpSecurity 中使用 requestMatchers().permitAll() —— 仍走过滤器链,但无条件放行;
    • 使用 WebSecurityCustomizer —— 跳过过滤器链,性能更高,但 6.x 已标废弃。
  5. 生产级注意:Swagger、Actuator、Druid 等常用端路径也要一并放行,否则线上 403 直接 P0 故障。

答案

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    /**
     * 禁用所有静态资源安全拦截 —— Spring Security 6.x 官方推荐写法
     */
    @Bean
    public SecurityFilterChain staticResourceChain(HttpSecurity http) throws Exception {
        // 1. 只针对静态资源建立一条链,优先级高于其他链
        return http
                // 只匹配常见静态资源路径,注意:**不带 /static 前缀**
                .securityMatchers(match -> match
                        .requestMatchers("/css/**", "/js/**", "/images/**",
                                         "/fonts/**", "/*.ico", "/*.txt"))
                // 2. 直接放行,不再校验会话、csrf、headers 等
                .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
                // 3. 关闭所有安全过滤器,避免性能浪费
                .csrf(csrf -> csrf.disable())
                .headers(headers -> headers.disable())
                .sessionManagement(s -> s.disable())
                .build();
    }

    /**
     * 业务接口链,优先级低于上面链,因此静态资源不会进入本链
     */
    @Bean
    public SecurityFilterChain businessChain(HttpSecurity http) throws Exception {
        return http
                .securityMatchers(match -> match
                        .requestMatchers("/api/**", "/admin/**"))
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/api/open/**").permitAll()
                        .anyRequest().authenticated())
                .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
                .build();
    }
}

关键点说明:

  • 使用 securityMatchers() 限定当前链生效范围,确保静态资源与业务接口互不干扰;
  • 路径匹配必须去掉 /static 前缀,与 Spring Boot 默认映射保持一致;
  • 把静态资源链放在业务链之前,利用 Bean 加载顺序保证优先级;
  • 禁用 csrf、headers、session,让静态资源请求零过滤器开销,压测 QPS 提升 10%+;
  • 如果项目仍用 Spring Security 5.x,只需把 securityMatchers() 换成 antMatcher("/css/**")...,但必须去掉 @EnableWebSecurity 继承 WebSecurityConfigurerAdapter 的旧写法,否则会被面试官直接判为过时技术栈。

拓展思考

  1. 生产环境往往把静态资源托管到 OSS + CDN,此时需要让 Spring Security 对 CDN 回源地址也放行,并在 Nginx 层做 Referer 防盗链,否则回源 403 会导致全网资源 404。
  2. 若项目采用 前后端分离 + SPA,通常会把 index.html 也当成静态资源,但必须单独加一条规则放行 /index.html,否则刷新页面 302 到登录页,用户体验极差。
  3. 在 云原生容器场景下,Actuator 健康检查端口 (/actuator/health) 与业务端口共用,务必在静态资源链之外再建一条“健康检查链”,否则 readinessProbe 被 403,Pod 会一直重启。
  4. 如果公司要求零信任架构,可以不直接放行静态资源,而是让前端把资源打到 JWT 匿名 Token 里,走 /public/** 接口统一鉴权,既满足安全合规,又能利用 CDN 缓存,这是阿里系金融项目的常用做法。