反向代理背后的 Springfox Swagger UI [英] Springfox Swagger UI behind reverse proxy

查看:56
本文介绍了反向代理背后的 Springfox Swagger UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 Swagger API 文档配置了一个 Spring Boot 应用程序并配置了 Swagger UI.

我还在一个反向代理后面运行我的后端应用程序,该代理将所有请求从 host:port/api 映射到 backend_host:port/,当在我映射的本地主机上运行时localhost:8082/api.在生产中应用了类似的映射.

当我从 localhost:8082/api/swagger-ui.html 打开 Swagger UI 时,它会在标题下方显示以下几行:

<块引用>

[ 基本 URL: localhost:8080 ]

在 Swagger UI (

I have configured a Spring Boot application with Swagger API documentation and configured Swagger UI.

I also run my backend application behind a reverse proxy that maps all requests from host:port/api to backend_host:port/, when running locally on localhost I map localhost:8082/api. In production a similar mapping is applied.

When I open the Swagger UI from localhost:8082/api/swagger-ui.html it shows the following lines below the title:

[ Base URL: localhost:8080 ]
http://localhost:8082/api/v2/api-docs

When I invoke any rest operation swagger always tries to perform it against localhost:8080 which then fails due to the same origin policy.

I am aware of using pathProvider but it only affects the base URL's path part, not the domain and port. So I can only use it to change the base URL to localhost:8080/api but I would need it to change to localhost:8082/api. Is there a way to set the host dynamically to the current host and port that is active in the browser?

.pathProvider (new RelativePathProvider (servletContext) {
                @Override
                public String getApplicationBasePath() {
                    return "/api";
                }
               })

解决方案

In my case with a spring-boot:2.2.6 application with springdoc-openapi-ui:1.3.0 (that also has embedded the swagger UI), I solved the proxy problem setting the server URL in this way:

@Configuration
public class OpenApiConfig {

  @Value("${server}")
  private String url;

  @Bean
  @Profile("prod")
  public OpenAPI customConfiguration() {
    return new OpenAPI()
        .servers(Collections
            .singletonList(new Server().url(url))) //real public URL
        .components(new Components())
        .info(new Info().title("Dummy API Docs")
            .description("Dummy REST API documentation"));
  }
}

This change is reflected in the contract (https://real-domain.com/api-docs):

And in the Swagger UI (https://real-domain.com/swagger-ui/index.html?configUrl=/api-docs/swagger-config)

这篇关于反向代理背后的 Springfox Swagger UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆