为了应对安全扫描,再生产环境下关闭swagger ui
1、项目中关闭swagger
在这里用的是config配置文件的方式关闭的
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {@Value("${swagger.enable}")private Boolean enable;@Beanpublic Docket swaggerPersonApi10() {return new Docket(DocumentationType.SWAGGER_2).enable(enable) //配置在该处生效.select().apis(RequestHandlerSelectors.basePackage("com.unidata.cloud.logservice.api.controller")).paths(PathSelectors.any()).build().apiInfo(apiInfo());}private ApiInfo apiInfo() {return new ApiInfoBuilder().version("1.0").title("").contact(new Contact("", "", "")).description("").build();}}
在application.properties中增加
swagger.enable: false
来控制关闭,如果想开启就改为true
2、到这里其实已经关闭swagger 了,但是安全扫描还是不能通过,因为访问swagger-ui.html路径会跳出提示swagger已关闭的页面,而安全扫描只要返回的页面中含有swagger的字符,就会不通过,这里还需要一步,让访问swagger-ui.html页面直接返回404
首先新增一个监听config
public class SwaggerInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String requestUri = request.getRequestURI();if (requestUri.contains("swagger-ui")) {response.sendRedirect("/404"); // 可以重定向到自定义的错误页面return false;}return true;}
}
然后在之前的config中添加一段代码
@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new SwaggerInterceptor()).addPathPatterns("/**");}
好的,到这里就已经彻底关闭swagger了