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

Spring Boot 3中Swagger UI的permitAll()不生效,访问需输入凭证

问题解决:Spring Boot 3 + JWT 集成 Swagger UI 需输入凭证

核心原因

Springfox 3.0.0 未适配 Spring Boot 3(基于 Spring Framework 6),二者存在兼容性问题,这是你配置了端点仍被要求输入凭证的主要原因。Springfox 已停止维护,Spring Boot 3 环境下推荐使用 Springdoc OpenAPI 作为 Swagger UI 的替代方案。

解决方案步骤

1. 替换依赖

移除所有 Springfox 相关依赖,添加 Springdoc OpenAPI 适配 Spring Boot 3 的依赖:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version>
</dependency>

版本可根据你的 Spring Boot 3 具体版本调整,建议选用与 Spring Boot 3 兼容的最新稳定版

2. 修正 Security 配置

调整 SecurityConfiguration,确保 Springdoc 的核心端点被允许匿名访问,同时可移除不必要的 httpBasic 配置(若你的认证完全依赖 JWT):

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration {

    private final JwtAuthenticationFilter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                    // 放行认证端点与Swagger相关端点
                    .requestMatchers("/api/v1/auth/**", 
                                     "/v3/api-docs/**", 
                                     "/swagger-ui/**", 
                                     "/swagger-ui.html")
                    .permitAll()
                    .anyRequest().authenticated()
            )
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authenticationProvider(authenticationProvider)
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}

若必须保留 httpBasic,需确保上述端点的 permitAll() 优先级高于 Basic 认证规则,避免触发弹窗

3. (可选)配置 Swagger 元数据

添加自定义配置类,设置 API 文档的基础信息:

@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("JWT 认证 API")
                        .version("1.0")
                        .description("基于 Spring Boot 3 和 JWT 的接口文档"));
    }
}

验证

启动应用后访问 http://localhost:8080/swagger-ui/index.html(Springdoc 的 UI 路径为 /swagger-ui/index.html,区别于 Springfox 的 /swagger-ui/),即可正常访问 Swagger UI,无需输入凭证。

内容的提问来源于stack exchange,提问作者Stefano Suunto Di Blasio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:44:50