springboot访问静态资源与整合swagger-bootstrap-ui的doc.html访问冲突问题(SpringSecurity)
项目场景:
毕业设计完成一个springboot+vue的前后端分离项目,整合了SpringSecurity安全框架和swagger2,并使用swagger-bootstrap-ui第三方接口文档ui。
关于spring security整合swagger2使用swagger-bootstrap-ui(在放行了静态资源后放行doc.html失败的问题)
问题描述
由于需要实现图片的上传下载功能,需要spring security放行静态资源,此前swagger-bootstrap-ui文档是可以放行并访问成功的,放行静态资源后doc.html就访问失败了。
放行静态资源前,此时doc.html可以正常访问。
/**
* 放行
* @param web
* @throws Exception
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(
"/login",
"/logout",
"/css/xx",
"/js/xx",
"/index.html",
"favicon.ico",
"/doc.html",
"/webjars/**",
"/swagger-resources/**",
"/v2/api-docs/**",
"/captcha",
"/user/register",
"/ws/**"
);
}
此时需要实现图片上传下载功能,随后放行了静态资源,添加了一个配置文件 WebMvcConfig.java
//添加如下三个放行路径
"/image/uploadImage",
"/static/**",
"/static/image"
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
/**
* 配置静态资源
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}
随后发现swagger-bootstrap-ui接口文档http:localhost:8081/doc.html无法正常访问。
原因分析:
经过检查发现去除掉WebMvcConfig.java这个配置文件后访问又恢复正常。冲突应该出现在这里。应该是在静态资源配置后默认将http:localhost:8081/doc.html视为了静态资源访问,但又寻找未果。
解决方案:
在配置文件中添加关于doc.html的配置以求与静态资源访问区分开
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
/**
* 配置静态资源
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//addResoureHandler:指的是对外暴露的访问路径 addResourceLocations:指的是内部文件放置的目录
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath*:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
然后接口文档就可以正常访问了
如果还遇到奇怪的问题可以去knife4j官方文档看一下
https://doc.xiaominfo.com/
还在摸索中,欢迎各位朋友交流,大佬们批评指正。