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

Swagger UI绕过Spring Boot接口认证问题求助

解决Swagger UI绕过Spring Security认证的问题

我之前踩过完全一样的坑!用curl调接口能正常返回401未授权,但Swagger UI点一下就直接200,当时差点以为自己的安全配置白写了😅

问题根源

这种情况基本是两个原因导致的:

  • 要么你的Spring Security配置里,误把业务接口(比如/users)也加入了匿名放行的列表;
  • 要么是Swagger默认不会携带认证凭证,但你的安全规则对Swagger相关请求的处理,意外让业务接口的匿名请求也通过了。

而且之前搜到的“移除安全层”的方案完全是饮鸩止渴,生产环境根本不能这么搞,下面给你一套既保留安全认证,又能让Swagger正常工作的配置:

第一步:修正Spring Security配置

核心原则是:只放行Swagger的静态资源和文档接口,所有业务接口必须强制认证。

如果是Spring Security 6.x版本,配置如下:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                // 允许Swagger相关路径匿名访问(只放文档相关的,别碰业务接口)
                .requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**").permitAll()
                // 其他所有请求必须经过认证
                .anyRequest().authenticated()
            )
            // 根据你的实际认证方式配置,比如HTTP Basic、JWT等,这里用Basic做示例
            .httpBasic(withDefaults());
        return http.build();
    }
}

如果是Spring Security 5.x版本,继承WebSecurityConfigurerAdapter的写法:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/swagger-ui/**", "/v3/api-docs/**", "/swagger-resources/**").permitAll()
                .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}

第二步:配置Swagger支持认证

光改安全配置还不够,Swagger默认不会自动携带认证信息,得让它支持在UI里输入凭证,发起请求时自动带上。这里以SpringDoc OpenAPI(Swagger 3)为例:

@Configuration
public class OpenApiConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
            // 定义认证方式,这里用HTTP Basic,你也可以换成JWT的Bearer Token
            .components(new Components()
                .addSecuritySchemes("basicAuth", new SecurityScheme()
                    .type(SecurityScheme.Type.HTTP)
                    .scheme("basic")))
            // 给所有接口默认加上认证要求
            .addSecurityItem(new SecurityRequirement().addList("basicAuth"));
    }
}

配置完之后,打开Swagger UI页面,右上角会出现一个「Authorize」按钮,点击后输入你的认证用户名和密码,再去调用/users接口:

  • 如果没输入凭证或者凭证错误,会返回预期的401;
  • 如果凭证正确,就会返回200和数据。

这样就完美解决了curl和Swagger UI行为不一致的问题,同时保留了接口的安全认证。

内容的提问来源于stack exchange,提问作者AlikElzin-kilaka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:13:29