Spring Cloud Gateway Preflight Cors 错误 Angular

Spring Cloud Gateway Preflight Cors Error with Angular

我正在尝试使用具有 spring 安全性的 spring 云网关,并尝试通过 angular 调用其余 API 但我收到以下错误

Access to XMLHttpRequest at 'http://localhost:9090/api/v1/publishers/?pageNo=1&pageSize=10&sort=name,desc&sort=city,desc' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

根据文档https://cloud.spring.io/spring-cloud-gateway/multi/multi__cors_configuration.html

我必须在应用程序 yaml 文件中添加 globalcors。

这是我的完整 yaml 文件。

server:
  port: 9090
keycloak-client:
  server-url: http://keycloak-url:8080/auth
  realm: dev
spring:
  application:
    name: gateway
  security:
    oauth2:
      client:
        provider:
          keycloak:
            issuer-uri: ${keycloak-client.server-url}/realms/${keycloak-client.realm}
            user-name-attribute: preferred_username
        registration:
          keycloak:
            client-id: cei-backend
            client-secret: f4d3242b-1fee-4dab-a491-d91ac51d637f
  cloud:
    gateway:
      default-filters:
        - TokenRelay
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "http://localhost:4200"
            allowedHeaders: "*"
            allowedMethods:
            - GET
            - POST
            - DELETE
            - PUT
      routes:
        - id: publisher_route
          uri: http://localhost:8000
          predicates:
            - Path=/api/v1/publishers/**
          filters:
            - RemoveRequestHeader=Cookie        
logging:
  level:
    org.springframework.cloud.gateway: DEBUG
    reactor.netty: DEBUG

以下是我的安全配置文件

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
                                                            ReactiveClientRegistrationRepository clientRegistrationRepository) {
        // Authenticate through configured OpenID Provider
        http.oauth2Login();
        // Also logout at the OpenID Connect provider
        http.logout(logout -> logout.logoutSuccessHandler(new OidcClientInitiatedServerLogoutSuccessHandler(
                clientRegistrationRepository)));
        // Require authentication for all requests
        http.authorizeExchange().anyExchange().authenticated();
        // Allow showing /home within a frame
        http.headers().frameOptions().mode(Mode.SAMEORIGIN);
        // Disable CSRF in the gateway to prevent conflicts with proxied service CSRF
        http.csrf().disable();

        return http.build();
    }

我从 angular 调用此 API 但我在预检请求中收到 CORS 错误。 我已经尝试了一切,但不知道我在哪里犯了错误。有什么想法吗?

我通过将 Angular App 移到 API 网关后面解决了这个问题,并在 API 网关和微服务

中添加了以下代码

在API网关

http.cors();

在微服务中

@Configuration
@EnableWebMvc
public class RestServiceCorsApplication implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

HttpMethod.OPTIONS 添加到您允许的方法中。使用 OPTIONS 方法向服务器发送预检请求。所以您的配置应该如下所示:

allowedMethods:
        - GET
        - POST
        - DELETE
        - PUT
        - OPTIONS

此外,您的路由必须包含 OPTIONS 方法。例如:

spring.cloud.gateway.routes[0].predicates[1] = Method=GET,POST,OPTIONS