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

网友投稿 818 2022-07-23


目录swagger配置正式环境中不可访问如何在生产环境中禁止swagger了?以下是正式环境访问swagger无法打开的说明总结了以下几个解决方案

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 即可访问。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java中NoClassDefFoundError 和 ClassNotFoundException的区别
下一篇:mybatis插入数据后如何返回新增数据的id值
相关文章

 发表评论

暂时没有评论,来抢沙发吧~