spring-bootmicroservicesopenapispringdoc-openapi-ui

Spring Cloud APIGW, Spring Boot and OpenAPI issue - CORS issue


I am using Spring Boot and Microservices stack using Spring Cloud APIGW. I am using the same code mentioned here: https://piotrminkowski.com/2020/02/20/microservices-api-documentation-with-springdoc-openapi/

When I hit any endpoint, I don't see response is coming and getting below error.

Access to fetch at 'http://192.168.0.2:49382/' from origin 'http://localhost:8060' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Source code: https://github.com/piomin/sample-spring-microservices-new

enter image description here


Solution

  • I was able to fix it by myself looking at suggestion here: Spring Cloud Gateway and Springdoc OpenAPi integration and https://github.com/springdoc/springdoc-openapi/issues/1144

    I had to add below in apigw-service in application.properties file

    server:
      forward-headers-strategy: framework
    

    Also, in each microservice, you need to add below bean

    @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurer() {
    
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
                }
            };
        }