Knife4j是一个集Swagger2 和 OpenAPI3为一体的增强解决方案,官网地址:Knife4j · 集Swagger2及OpenAPI3为一体的增强解决方案. | Knife4j
考虑到安全性问题,在实际服务部署到生产环境后就需要禁用到swagger页面的展示,这个时候只需要进行如下配置即可实现该功能:
knife4j: production: true
是的,通过设置knife4j.production为true就意味着在生产环境下,这个时候就无法打开swagger对应页面,当你输入http://localhost:8081/doc.html页面会返回如下错误信息:
下面简单看下knife4j是如何实现该功能的,找到Knife4jAutoConfiguration这个类,看如下的Bean创建即可
// knife4j.productio为true时创建ProductionSecurityFilter对象
@Bean
@ConditionalOnMissingBean(ProductionSecurityFilter.class)
@ConditionalOnProperty(name = "knife4j.production", havingValue = "true")
public ProductionSecurityFilter productionSecurityFilter(Knife4jProperties knife4jProperties) {
boolean prod = false;
ProductionSecurityFilter p = null;
if (knife4jProperties == null) {
if (environment != null) {
String prodStr = environment.getProperty("knife4j.production");
if (logger.isDebugEnabled()) {
logger.debug("swagger.production:{}", prodStr);
}
prod = Boolean.valueOf(prodStr);
}
p = new ProductionSecurityFilter(prod);
} else {
p = new ProductionSecurityFilter(knife4jProperties.isProduction());
}
return p;
}
ProductionSecurityFilter类如其名,该类是一个Filter实现类,所以看下这个类的doFilter方法实现
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
if (production) {
String uri = httpServletRequest.getRequestURI();
// 判断uri是否是要被拦截的地址,被拦截地址有如下几个:
//
/*
public BasicFilter() {
urlFilters = new ArrayList<>();
urlFilters.add(Pattern.compile(".*?/doc\\.html.*", Pattern.CASE_INSENSITIVE));
urlFilters.add(Pattern.compile(".*?/v2/api-docs.*", Pattern.CASE_INSENSITIVE));
urlFilters.add(Pattern.compile(".*?/v2/api-docs-ext.*", Pattern.CASE_INSENSITIVE));
urlFilters.add(Pattern.compile(".*?/swagger-resources.*", Pattern.CASE_INSENSITIVE));
urlFilters.add(Pattern.compile(".*?/swagger-resources/configuration/ui.*", Pattern.CASE_INSENSITIVE));
urlFilters.add(Pattern.compile(".*?/swagger-resources/configuration/security.*", Pattern.CASE_INSENSITIVE));
// https://gitee.com/xiaoym/knife4j/issues/I6H8BE
urlFilters.add(Pattern.compile(".*?/swagger-ui.*", Pattern.CASE_INSENSITIVE));
urlFilters.add(Pattern.compile(".*?/v3/api-docs.*", Pattern.CASE_INSENSITIVE));
}*/
if (!match(uri)) {
chain.doFilter(request, response);
} else {
response.setContentType("text/palin;charset=UTF-8");
PrintWriter pw = response.getWriter();
// 下面信息就是页面展示的无权访问信息
pw.write("You do not have permission to access this page");
pw.flush();
}
} else {
chain.doFilter(request, response);
}
}