Search code examples
spring-bootswaggeropenapikongspringdoc

How to configure Spring OpenAPI UI behind Kong


I have a Spring Boot application and I'm using Kong as an API Gateway.

I would like to document my app's REST API with SpringDoc OpenAPI.

Everything works great locally, when I run my Spring Boot app as a standalone, but I'm facing a problem when accessing the Swagger/OpenAPI UI behind Kong.

This is my kong.yml:

services:
 - name: foo
   url: http://localhost:9000/foo
   routes:
   - name: foo-route
     paths:
      - /local/api/foo
     methods:
     - GET
     - POST
     - PUT
     - OPTIONS
     - DELETE
     - PATCH
     - HEAD

Assume that kong is on port 8000, and my Spring App is on port 9000.

When I hit Kong at http://localhost:8000/local/api/foo/swagger-ui.html, I get redirected to http://localhost:8000/foo/swagger-ui/index.html?configUrl=/foo/v3/api-docs/swagger-config, which is the wrong path.

How can I fix this issue?


Solution

  • Found a solution!

    On the Spring Boot side, since I'm using a version higher than 2.2, all is needed is the following bean:

    @Bean
    ForwardedHeaderFilter forwardedHeaderFilter() {
        return new ForwardedHeaderFilter();
    }
    

    and this configuration:

    server:
      forward-headers-strategy: framework 
    

    On the Kong side, since I'm using an outdated version (2.0.3), I need to add the following plugin to my kong.yml configuration file:

    plugins:     
     - name: request-transformer
       service: foo
       config:
        add:
         headers:
          - x-forwarded-prefix:/local/api/foo
    

    from my understanding, this is not needed in newer Kong versions: as long as the host has a trusted ip, the header x-forwarded-prefix will be added automatically.