7

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

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

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

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

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

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

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

2 回答 2

4

在我使用 spring-boot:2.2.6 应用程序和 springdoc-openapi-ui:1.3.0 (也嵌入了 swagger UI)的情况下,我解决了以这种方式设置服务器 URL 的代理问题:

@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 合约

在 Swagger UI 中(https://real-domain.com/swagger-ui/index.html?configUrl=/api-docs/swagger-config

Swagger UI 服务器列表

于 2020-04-16T23:33:06.387 回答
1

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

请配置代理以将标头X-Forwarded-Host设置为来自主机请求标头的值

说明:
在您的浏览器中,当您将访问一个 URL 时,例如。https://my.domain.com/api/swagger-ui.html

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

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

-> 所以 Swagger /apidocs enpoint 可以在响应 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>
于 2019-05-16T11:30:27.163 回答