首页 > 其他 > 详细

在生产环境中禁用Swagger

时间:2020-12-18 10:13:31      阅读:91      评论:0      收藏:0      [点我收藏+]
一、采用的方案
1. 在class中
@Configuration
//配置是否开启swagger的访问的方式一,动态读取无法使用,@active@
//@Profile({"dev", "test", "local", "uat-local"})            
//配置是否开启swagger的访问的方式二,要在yml中添加对应配置
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")      
@EnableSwagger2 //Enable swagger 2.0 spec
public class SwaggerConfig {
    
2. 在yml文件中
# 是否启用swagger,true则启用
swagger:
  enable: true  
 
二、实现方案:
 
1. @Profile({"dev", "test", "local", "uat-local"})。实际使用中,配置文件为动态设置,无法使用方案一
spring: profiles: active: @active@
2. @ConditionalOnProperty(name = "swagger.enable", havingValue = "true") 。不需要开放访问则不配置或者配置为非true
# 是否启用swagger,true则启用 swagger: enable: true
3. 拦截器
@Component public class SwaggerInterceptor implements HandlerInterceptor {
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (StringUtils.trim(activeProfile).equals("uat") || StringUtils.trim(activeProfile).equals("prod")) {
      return false;
    } return true;
   }
...
 
@Configuration public class InterceptorConfig implements WebMvcConfigurer {
  //spring-boot 2.x 的写法
  @Override public void addInterceptors(InterceptorRegistry registry) {
    logger.info("拦截器注册", "SwaggerInterceptor", null);
    registry.addInterceptor(swaggerInterceptor).addPathPatterns(SWAGGER_UI_URL);
  }
...
4. 在nginx或者服务网关中处理
 
三、遇到的问题:
 
1. 测试过程中,方法一与方法二都无效,排查后确认原因:
  启动类中也有一个启动swagger的配置,所以在SwaggerConfig中失效的情况下,依然有效
@EnableSwagger2 public class Application
  解决方法:注释掉//@EnableSwagger2

在生产环境中禁用Swagger

原文:https://www.cnblogs.com/weijs/p/14153363.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!