Spring Security 6如何放行静态资源(静态文件、图片等)
Spring Security 6 中 WebSecurityCustomizer 的替代方案
在Spring Security 6里,WebSecurityCustomizer已被废弃,替代方式是直接在SecurityFilterChain配置中处理静态资源放行,或是通过securityMatcher缩小安全过滤范围,避免静态资源被安全过滤器拦截。
方案1:在authorizeHttpRequests中放行静态资源路径
Spring Boot默认的静态资源对应访问路径为/css/**、/js/**、/images/**、/webjars/**等(对应项目src/main/resources/static下的子目录),你可以直接在requestMatchers中添加这些路径并允许匿名访问:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{ httpSecurity .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(auth -> auth // 放行所有静态资源路径 .requestMatchers("/css/**", "/js/**", "/images/**", "/webjars/**") .permitAll() // 放行auth相关业务路径 .requestMatchers("/auth/**") .permitAll() // 其余请求需认证后访问 .anyRequest() .authenticated()) return httpSecurity.build(); }
方案2:使用securityMatcher缩小安全过滤范围
如果你的业务接口有统一前缀(比如/api/**),可以通过securityMatcher指定Spring Security仅处理特定前缀的请求,静态资源路径会自动被排除在安全过滤逻辑之外:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{ httpSecurity .csrf(AbstractHttpConfigurer::disable) // 指定仅处理/auth/**和/api/**路径的请求 .securityMatcher("/auth/**", "/api/**") .authorizeHttpRequests(auth -> auth .requestMatchers("/auth/**") .permitAll() .anyRequest() .authenticated()) return httpSecurity.build(); }
注意事项
- 不要直接使用
requestMatchers("/**").permitAll(),这会放行所有请求,包括需要认证的业务接口,存在严重安全风险。 - 确保配置的路径与静态资源实际访问路径匹配,比如
src/main/resources/static/css/main.css对应的访问路径是/css/main.css,因此配置/css/**即可覆盖该目录下所有资源。
内容的提问来源于stack exchange,提问作者Sany
相关产品推荐
相关产品推荐

