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

Spring无UI接口应用Swagger UI集成配置指导(免认证+测试环境)

刚好我之前处理过类似的Spring+Swagger集成需求,针对你的场景,我整理了一套完整的配置方案,涵盖环境开关、安全放行、资源映射和Swagger优化,一步步帮你实现要求:

1. 控制Swagger仅在测试环境启用

首先要确保Swagger的配置只在测试环境加载,避免生产环境暴露API文档。我们可以用Spring的@Profile注解来实现,把Swagger相关的配置隔离到测试环境专属的静态类中:

@SpringBootApplication
@ComponentScan(basePackages = {"x.x.x"})
public class XXApplication {
    public static void main(String[] args) {
        DefaultsUtil.setCommunity("1");
        SpringApplication.run(XXApplication.class, args);
    }

    // 仅在测试环境激活Swagger配置
    @Profile("test")
    @EnableSwagger2
    static class SwaggerConfig {
        @Bean
        public Docket api(){
            return new Docket(DocumentationType.SWAGGER_2)
                    .groupName("XX")
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.ariba.collab.platform.restengine"))
                    .paths(PathSelectors.any())
                    .build()
                    .apiInfo(new ApiInfo(
                            "Conversations", 
                            "A set of operations on Chats", 
                            "1.0.0", 
                            "http://xxx.Policy.html", 
                            new Contact("Team", null, "xxx@yyy.com"),
                            null, 
                            null
                    ));
        }
    }
}

同时,确保你的测试环境配置文件(比如application-test.yml)中没有禁用Swagger,生产环境(application-prod.yml)则完全不会加载这些配置。

2. 配置安全放行规则(Swagger路径无需认证)

因为你的应用所有API都需要授权,所以必须在安全配置中单独放行Swagger相关的所有路径,确保访问Swagger UI和接口文档时无需认证。假设你用的是Spring Security,配置如下:

如果你用的是Spring Security 5.7+(推荐新写法)

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                        // 放行所有Swagger相关路径和自定义首页
                        .requestMatchers(
                                "/swagger-ui/**",
                                "/v2/api-docs",
                                "/swagger-resources/**",
                                "/webjars/**",
                                "/swagger.json",
                                "/index.html"
                        ).permitAll()
                        // 其他所有API必须认证
                        .anyRequest().authenticated()
                )
                // 凭证错误时返回400(符合你的需求)
                .exceptionHandling(ex -> ex
                        .authenticationEntryPoint((request, response, authException) -> {
                            response.setStatus(HttpStatus.BAD_REQUEST.value());
                            response.getWriter().write("Invalid credentials");
                        })
                );
        return http.build();
    }
}

如果你用的是旧版WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 放行Swagger和自定义首页路径
                .antMatchers(
                        "/swagger-ui/**",
                        "/v2/api-docs",
                        "/swagger-resources/**",
                        "/webjars/**",
                        "/swagger.json",
                        "/index.html"
                ).permitAll()
                // 其他API必须认证
                .anyRequest().authenticated()
                .and()
                // 凭证错误返回400
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    response.setStatus(HttpStatus.BAD_REQUEST.value());
                    response.getWriter().write("Invalid credentials");
                });
    }
}
3. 配置资源处理器(Swagger UI静态资源映射)

如果你的WebConfig继承了WebMvcConfigurer,需要手动添加资源映射,确保Swagger UI的静态资源能被正确访问。同时如果你添加了自定义的index.html(放在src/main/resources/static/目录下),也需要映射:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射Swagger UI的官方静态资源(来自webjars依赖)
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/");
        
        // 映射自定义的index.html(如果需要)
        registry.addResourceHandler("/index.html")
                .addResourceLocations("classpath:/static/");
    }
}

注意:如果你的项目依赖了spring-boot-starter-web,其实默认已经会处理静态资源,但如果自定义了WebMvc配置,就需要手动添加这段映射,避免Swagger UI加载失败。

4. 验证效果
  • 测试环境:启动应用后,访问http://localhost:端口/swagger-ui/index.html可以直接打开Swagger UI,无需认证;调用其他API接口时,若凭证错误会返回400响应。
  • 生产环境:Swagger的配置类不会被加载,访问任何Swagger相关路径都会返回404,完全符合生产环境的安全要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:53:45