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

使用Spring Security时如何配置才能正常访问swagger-ui界面

解决Spring Security拦截Swagger-UI访问的配置方案

核心问题原因

你当前配置不生效主要有两个问题:

  • 你使用的是Swagger2版本(DocumentationType.SWAGGER_2),却在Security放行规则中配置了OpenAPI 3.0对应的/v3/api-docs/**路径,路径不匹配导致放行规则未触发
  • 现有SwaggerConfig类缺少@EnableSwagger2启用注解,会导致Swagger资源本身未正常加载

1. 修正Swagger配置

给你的SwaggerConfig类添加启用注解,修正后代码如下:

@Configuration
@EnableSwagger2 // 新增Swagger2启用注解
public class SwaggerConfig  {
    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.safariwebstore008"))
                .paths(PathSelectors.any())
                .build();
    }
}

2. 修正Spring Security放行路径

Swagger2需要放行的核心资源路径如下,同时在两处配置中添加放行规则即可:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .csrf().disable()
            .authorizeRequests()
            // 新增Swagger2相关路径放行
            .antMatchers("/v2/api-docs", "/swagger-resources/**", 
                        "/swagger-ui.html", "/webjars/**",
                        "/register","/authenticate").permitAll()
            .antMatchers().hasAnyRole()
            .anyRequest().authenticated().and()
            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    httpSecurity.headers().frameOptions().disable();
}

@Override
public void configure(WebSecurity web) throws Exception {
    // 替换为Swagger2对应的路径规则
    web.ignoring().antMatchers(
        "/v2/api-docs",
        "/swagger-resources/**",
        "/swagger-ui.html",
        "/webjars/**"
    );
}

3. 验证效果

配置修改完成后重启项目,访问http://你的项目域名或IP:端口/swagger-ui.html即可正常打开接口文档页面。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:39:04