Spring Cloud APIGW、Spring Boot 和 OpenAPI 问题 - CORS 问题

问题描述 投票:0回答:3

我正在使用 Spring Boot 和使用 Spring Cloud APIGW 的微服务堆栈。我使用此处提到的相同代码:https://piotrminkowski.com/2020/02/20/microservices-api-documentation-with-springdoc-openapi/

当我到达任何端点时,我没有看到响应即将到来并且低于错误。

从源“http://localhost:8060”获取“http://192.168.0.2:49382/”的访问已被 CORS 策略阻止:“Access-Control-Allow-Origin”标头不存在请求的资源。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

源代码:https://github.com/piomin/sample-spring-microservices-new

enter image description here

spring-boot microservices openapi springdoc-openapi-ui
3个回答
3
投票

我能够自己修复它,查看这里的建议:Spring Cloud Gateway 和 Springdoc OpenAPI 集成https://github.com/springdoc/springdoc-openapi/issues/1144

我必须在

application.properties
文件中的 apigw-service 中添加以下内容

server:
  forward-headers-strategy: framework

另外,在每个微服务中,您需要添加以下bean

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {

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

1
投票

你应该添加 swagger 配置

@Configuration
@OpenAPIDefinition(servers = {
    @Server(url = "/", description = "Default Server URL")
})
public class SwaggerConfiguration {

@Bean
public OpenAPI customOpenAPI(@Value("springdoc-openapi-ui") String serviceTitle, @Value("1.6.12") String serviceVersion) {
    final String securitySchemeName = "bearerAuth";
    return new OpenAPI()
            .components(
                    new Components().addSecuritySchemes(
                            securitySchemeName,
                            new SecurityScheme()
                                    .type(SecurityScheme.Type.HTTP)
                                    .scheme("bearer")
                                    .bearerFormat("JWT")
                    )
            )
            .security(List.of(new SecurityRequirement().addList(securitySchemeName)))
            .info(new Info().title(serviceTitle).version(serviceVersion));
}
}

0
投票

通过添加以下 application.properties 对我有用

server.forward-headers-strategy: framework

在Springboot-3.3.2版本中,并使用了swagger UI生成maven依赖

     <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
        <version>2.5.0</version>
    </dependency>

本来我添加了Java代码,实际上不是必需的。我使用 NGROCK 服务器进行了测试。

© www.soinside.com 2019 - 2024. All rights reserved.