"填坑" 之 swagger2 页面无法访问:This is common when using dynamic servlet registration or when the API is

本文详细解析了在使用Spring Boot和Spring Security搭建的项目中,遇到Swagger页面无法正常访问的问题。介绍了问题的原因分析及解决方案,通过在自定义配置类中添加对Swagger的过滤,成功解决了权限控制导致的页面访问问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误信息

Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually: 

基础包

spring boot :2.1.2.RELEASE

swagger2:2.9.2

问题描述

通过spring-security搭建token认证工程时,想使用swagger来做接口测试,项目启动成功后发现swagger页面无法正常访问,页面错误信息如下:

原因分析

出现这个问题主要的可能原因是swagger页面权限控制被拦截了,只要去掉对swagger地址的拦截就可以了

解决方法

网上查到很多解决方式,

1. 有的说:让你的Application 启动类继承SpringBootServletInitializer,然后scanBasePackages包范围内都扫描。

2. swagger的版本问题

3. 没有添加@EnableSwagger2注解

不过这些我都检查过没问题,并没有解决我的问题。其实我们只要在自定义配置类中添加对swagger的过滤即可

配置内容

@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) {
        web
                .ignoring()
                .antMatchers(
                        "swagger-ui.html",
                        "**/swagger-ui.html",
                        "/favicon.ico",
                        "/**/*.css",
                        "/**/*.js",
                        "/**/*.png",
                        "/**/*.gif",
                        "/swagger-resources/**",
                        "/v2/**",
                        "/**/*.ttf"
                );
        web.ignoring().antMatchers("/v2/api-docs",
                "/swagger-resources/configuration/ui",
                "/swagger-resources",
                "/swagger-resources/configuration/security",
                "/swagger-ui.html"
        );
    }
	
}

 

重启项目,swagger页面正常访问

以上是个人的”填坑“警示,由于个人能力所限,如有描述有误或者其他处理方式,欢迎评论并指教

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值