反向代理背后的Springfox Swagger UI

时间:2018-04-24 19:46:48

标签: swagger-ui springfox

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

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

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

  

[基本网址:localhost:8080]
  http://localhost:8082/api/v2/api-docs

当我调用任何休息操作时,swagger总是尝试对localhost:8080执行它,然后由于相同的源策略而失败。

我知道使用pathProvider但它只会影响基本网址的路径部分,而不会影响域和端口。所以我只能使用它将基本URL更改为localhost:8080 / api但是我需要它更改为localhost:8082 / api。有没有办法将主机动态设置为浏览器中活动的当前主机和端口?

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

2 个答案:

答案 0 :(得分:2)

对于使用springdoc-openapi-ui:1.3.0的spring-boot:2.2.6应用程序(它也嵌入了swagger UI),我解决了设置服务器URL的代理问题: / p>

@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"));
  }
}

此更改反映在合同(https://real-domain.com/api-docs)中:

OpenAPI contract

在Swagger用户界面(https://real-domain.com/swagger-ui/index.html?configUrl=/api-docs/swagger-config

Swagger UI server list

答案 1 :(得分:1)

我认为在您的情况下,您需要配置代理以设置HTTP标头
(将转发到您的目标后端)
“通知” Swagger端点以在/ apidocs端点中返回自定义URL。

请配置代理以将标头 X-Forwarded-Host 设置为 Host 请求标头

中的值

说明:
在浏览器中,当您访问网址时,例如https://my.domain.com/api/swagger-ui.html

代理应创建并转发标头X-Forwarded-Host: my.endpoint.com

到您的后端localhost:8082/api/swagger-ui.html

->,因此Swagger / apidocs可以在响应JSON中考虑此标头。

我自己的情况-在Microsoft IIS中:

我需要配置Microsoft IIS,以在HTTPS域的8080端口上从Apache Tomcat提供Swagger IU,
所以我需要进行以下配置:

<serverVariables>
    <set name="HTTP_X_FORWARDED_HOST" value=“{HTTP_HOST}” />
    <set name="HTTP_X_FORWARDED_PROTO" value="https" />
</serverVariables>