swagger配置环境不可访问

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

swagger配置环境不可访问

大-哥   2022-06-19 我要评论

swagger配置正式环境中不可访问

Swagger是我们常用的API Doc工具,非常便于开发人员调试,后台和前端开发人员协作,以及对外公布API使用。

如何在生产环境中禁止swagger了?

@Profile("beta")  // 只允许在测试服务器访问Swagger

package com.demo.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
 * @author HHM
 */
@Configuration
@EnableSwagger2
@Profile("beta")
public class SwaggerConfig {
    @Bean
    public Docket buildDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(buildApiInf())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo buildApiInf() {
        return new ApiInfoBuilder()
                .title("管理系统接口文档")
                .description("后台管理 API 接口文档")
                .version(DocumentationType.SWAGGER_2.getVersion())
                .build();
    }
}

以下是正式环境访问

swagger无法打开的说明

最近项目集成swagger2,结果本地swagger-ui.html可以打开,但是线上环境却无法打开。倒腾了一番终于解决问题

总结了以下几个解决方案

1.@EnableWebMvc注解必须去掉!

2.请实现WebMvcConfigurer,并添加如下代码

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
  registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
  registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

3.检查配置文件application.properties

将如下配置去掉,或者改成true:

spring.resources.add-mappings=false

将如下配置去掉:

spring.resources.static-locations: classpath:/webapp/

4.查看nginx配置(当前项目踩坑点)

检查前端代码,发现nginx配置有如下一段:

location /api/swagger-ui.html{
        proxy_pass http://server-service:8080/;
        proxy_set_header X-Real-IP $remote_addr;
        client_max_body_size    1000m;
}

由于当前应用部署在k8s环境中,后端的api地址恰好为http://server-service:8080/,所以这个配置会导致请求直接转发到后端接口,导致无法访问页面。

事实上,针对swagger,前端nginx不需要做任何映射,直接请求 http:// {后端公网host}/swagger-ui.html 即可访问。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们