'Spring Cloud Gateway and Springdoc OpenAPi integration
I was able to integrate Spring Cloud Gateway with the Springdoc OpenAPI in an small application with an architecture oriented to microservices. But now, when I open the Swagger UI to test the endpoint of my controller (StudentController) I realized that the @RequestMapping at the root level of the controller is not included in the URL of the endpoint to test. The routes definition are the following:
routes:
- id: students-service
uri: lb://STUDENTS-SERVICE
predicates:
- Path=/students/**
filters:
- RewritePath=/students/(?<path>.*), /$\{path}
- id: openapi
uri: http://localhost:${server.port}
predicates:
- Path=/v3/api-docs/**
filters:
- RewritePath=/v3/api-docs/(?<path>.*), /$\{path}/v3/api-docs
And the StudentController is the following:
@RestController
@RequestMapping("/api/v1")
@Tag(name = "Students")
public class StudentQueryController {
@GetMapping("/message")
public String dummyGet() {
return "Student Service Dummy GET";
}
}
In the Swagger UI I expected to get the URL like "http://localhost:8060/students/api/v1/message", but I got "http://localhost:8060/api/v1/message".
Someone would be kind to help me with this issue, please? Thanks in advance.
Solution 1:[1]
If you have the springdoc configured in an application behind a proxy like Spring Cloud Gateway you should configure this property in your service application:
server.forward-headers-strategy=framework
This property was introduced in spring-boot 2.2.0.
Explanation:
When the request passes through the Spring Cloud Gateway some proxy-related headers will be added to the request (like x-forwarded-host
, x-forwarded-proto
, etc).
With this property set your application will use those headers to make the right redirect. Instead of redirecting to /api/v1/message
it will redirect to /students/api/v1/message
(since the /students
prefix will be available in the x-forwarded-prefix
header).
Only use this setting if the proxy behind all your applications configures correctly those headers and you can trust this proxy.
If you restrict all your applications to be accessed only through the Spring Cloud Gateway you will be fine.
You can read more about this parameter and behavior here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |