You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3迁移后OpenAPI URL仍需Basic认证的问题求助

Spring Boot 3.0.0-RC2中OpenAPI URL仍需认证的问题解决

问题背景

将REST应用从Spring Boot 2.7.5迁移至3.0.0-RC2后,配置/openapi/openapi.yml无需认证,但该URL仍要求Basic认证。2.7.5中使用antMatchers的配置正常,3.0.0-RC2替换为requestMatchers后失效,仅路径匹配方法修改,其他配置一致。

可能的解决方案

1. 明确指定请求方法

Spring Security 6中requestMatchers默认匹配所有请求方法,显式指定HTTP方法可避免匹配歧义。尝试为OpenAPI路径添加方法限制:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

  @Bean
  public SecurityFilterChain configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeHttpRequests((requests) -> requests
            .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .requestMatchers(HttpMethod.GET, "/openapi/openapi.yml").permitAll()
            .anyRequest().authenticated())
        .httpBasic();
    return http.build();
  }
}

2. 显式使用AntPathMatcher

Spring Security 6默认使用PathPatternParser作为路径匹配器,而旧版本依赖AntPathMatcher。若你的路径是Ant风格,可显式指定匹配器:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

  @Bean
  public SecurityFilterChain configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeHttpRequests((requests) -> requests
            .requestMatchers(new AntPathRequestMatcher("/**", "OPTIONS")).permitAll()
            .requestMatchers(new AntPathRequestMatcher("/openapi/openapi.yml")).permitAll()
            .anyRequest().authenticated())
        .httpBasic();
    return http.build();
  }
}

也可以全局配置路径匹配器:

@Bean
public PathMatcher pathMatcher() {
    return new AntPathMatcher();
}

3. 检查SecurityFilterChain优先级

若存在多个SecurityFilterChain Bean,可能因顺序问题导致当前配置未生效。通过@Order注解指定优先级,确保该配置先被处理:

@Configuration
@EnableWebSecurity
@Order(1) // 数值越小优先级越高
public class WebSecurityConfig {
  // ... 原有配置
}

4. 升级至最新版本

3.0.0-RC2是预发布版本,可能存在已知bug。尝试升级到Spring Boot 3的正式版或后续RC版本,验证问题是否已修复。

内容的提问来源于stack exchange,提问作者Thomas Oellrich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 17:10:24