springboot项目关闭swagger防止漏洞扫描

时间:2025-03-17 07:12:20

为了应对安全扫描,再生产环境下关闭swagger ui

1、项目中关闭swagger

在这里用的是config配置文件的方式关闭的

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {

    @Value("${}")
    private Boolean enable;
    @Bean
    public Docket swaggerPersonApi10() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(enable)    //配置在该处生效
                .select()
                .apis((""))
                .paths(())
                .build()
                .apiInfo(apiInfo());
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .version("1.0")
                .title("")
                .contact(new Contact("", "", ""))
                .description("")
                .build();
    }

}

在中增加

: false

来控制关闭,如果想开启就改为true

2、到这里其实已经关闭swagger 了,但是安全扫描还是不能通过,因为访问路径会跳出提示swagger已关闭的页面,而安全扫描只要返回的页面中含有swagger的字符,就会不通过,这里还需要一步,让访问页面直接返回404

首先新增一个监听config

public class SwaggerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestUri = ();
        if (("swagger-ui")) {
            ("/404"); // 可以重定向到自定义的错误页面
            return false;
        }
        return true;
    }
}

然后在之前的config中添加一段代码

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        (new SwaggerInterceptor()).addPathPatterns("/**");
    }

好的,到这里就已经彻底关闭swagger了