错误信息
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页面正常访问
以上是个人的”填坑“警示,由于个人能力所限,如有描述有误或者其他处理方式,欢迎评论并指教