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

如何排除Spring Boot中OpenAPI的/v3/api-docs路径的安全认证?

解决方案:排除OpenAPI路径的安全认证

只需修改SecurityFilterChain中的权限配置规则,将OpenAPI相关路径设置为允许匿名访问,再对其余请求启用认证即可。

修改后的filterChain方法代码如下:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http, KeycloakAuthenticationConverter authenticationConverter) throws Exception {
    http.authorizeHttpRequests((authorize) -> authorize
            // 放行OpenAPI相关路径,无需认证
            .requestMatchers("/v3/api-docs/**", "/v3/api-docs.yaml").permitAll()
            // 其余所有请求必须认证
            .anyRequest().authenticated())
        .csrf((csrf) -> csrf.disable())
        .oauth2ResourceServer((oauth2ResourceServer) -> oauth2ResourceServer.jwt((jwt) -> jwt.decoder(jwtDecoder())))
        .oauth2ResourceServer((oauth2) -> oauth2.jwt((jwt) -> jwt.jwtAuthenticationConverter(authenticationConverter)));
    return http.build();
}

关键点说明:

  • 规则顺序:Spring Security的权限规则是从上到下匹配,必须先定义放行规则,再设置全局认证规则,否则anyRequest().authenticated()会覆盖前面的放行规则。
  • 扩展路径:如果使用Swagger UI,还可以添加/swagger-ui/**、/swagger-ui.html等路径到requestMatchers中,确保UI界面也能匿名访问。
  • permitAll的作用:permitAll()已经包含允许匿名访问的逻辑,不需要额外添加.anonymous()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 12:30:19