为Spring云网关配置CORS策略

iqxoj9l9  于 2023-01-16  发布在  Spring
关注(0)|答案(5)|浏览(184)

我有Spring Cloud gateway运行在单独的服务器上,配置如下:

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/*]':   (I also tried '[/**]':)
            allowedOrigins: "http://localhost:3000"
            allowedMethods:
              - GET
              - POST

但每次从React应用程序我得到:
CORS策略已阻止从源"http://localhost:3000"访问位于"http://11.1.1.1:8080/api/support/tickets/create"的XMLHttpRequest:对印前检查请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头。
您知道Spring Boot 2.6.2/Spring cloud 2021.0.0如何解决此问题吗?
完整代码:http://www.github.com/rcbandit111/Spring_Cloud_Gateway_POC
POST请求:

Request URL: http://1.1.1.1:8080/api/merchants/onboarding/bank_details
Referrer Policy: strict-origin-when-cross-origin
Accept: application/json, text/plain, */*
Content-Type: application/json
Referer: http://localhost:3000/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36

Post request Payload:
{"currency":"HNL","iban":"dssvsdvsdv"}

选项请求:

Request URL: http://1.1.1.1:8080/api/merchants/onboarding/bank_details
Request Method: OPTIONS
Status Code: 403 Forbidden
Remote Address: 1.1.1.1:8080
Referrer Policy: strict-origin-when-cross-origin

回复:

HTTP/1.1 403 Forbidden
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
content-length: 0

OPTIONS请求标头:

OPTIONS /api/merchants/onboarding/bank_details HTTP/1.1
Host: 1.1.1.1:8080
Connection: keep-alive
Accept: */*
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36
Sec-Fetch-Mode: cors
Referer: http://localhost:3000/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
hwamh0ep

hwamh0ep1#

您是否通过--proxy-conf运行FE应用程序以进行重定向?我不太精通FE,但不要使用changeOrigin:true。如果必须使用changeOrigin:true,它只对GET有效,对其他的你可能需要做一些类似的事情。要使用proxy-conf,我们通常有一个proxy.conf.json,内容如下:

{
  "/api/*": {
    "target": "http://external-gateway-url",
    "secure": false,
    "logLevel": "debug"
  }
}

然后在运行应用程序时使用--proxy-config proxy.conf.json。我的FE知识已经过时了。您可能希望看起来像this
如果没有,并且调用是直接的,则网关中的以下配置(代理也需要)应该起作用:

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "http://localhost:3000"
            allowedHeaders: "*"
            allowedMethods:
            - GET
            - POST
rkttyhzu

rkttyhzu2#

我有一个类似的问题,我做了以下:
我的应用程序.yml包含将CORS配置添加到每条路线:

spring:
  cloud:
    gateway:
      globalcors:
        add-to-simple-url-handler-mapping: true

然后我配置了一个Spring标准的CorsWebFilterBean。注意,对于生产,您不应该使用 * 作为AllowedOrigins属性。对于开发目的,这是非常好的。

@Configuration
public class CorsConfiguration extends org.springframework.web.cors.CorsConfiguration {

  @Bean
  public CorsWebFilter corsFilter() {
    org.springframework.web.cors.CorsConfiguration corsConfiguration = new org.springframework.web.cors.CorsConfiguration();
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.addAllowedOrigin("*");
    corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"));
    corsConfiguration.addAllowedHeader("origin");
    corsConfiguration.addAllowedHeader("content-type");
    corsConfiguration.addAllowedHeader("accept");
    corsConfiguration.addAllowedHeader("authorization");
    corsConfiguration.addAllowedHeader("cookie");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", corsConfiguration);
    return new CorsWebFilter(source);
  }
}

注意:我有版本2. 3. 9.发布的Spring Boot 和 Spring 云版本是hoxtonidersr10。

sulc1iza

sulc1iza3#

查看MDN Web Docs about CORS中标题为 * 简单请求 * 的部分:
Content-Type标头中指定的媒体类型仅允许以下类型/子类型组合:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

由于您将值application/json用于请求的Content-Type标头,因此需要在CORS配置中允许该标头:

cors-configurations:
  '[/**]':
    allowedOrigins: "http://localhost:3000"
    allowedMethods:
      - GET
      - POST
    allowedHeaders:
      - Content-Type
lnxxn5zx

lnxxn5zx4#

您可以在安全类中添加cors配置。

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
    private SecurityRepository securityRepository;

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http){
        http
                .cors().configurationSource(request -> {
                    CorsConfiguration configuration = new CorsConfiguration();
                    configuration.setAllowedOrigins(List.of("http://localhost:3000"));
                    configuration.setAllowedMethods(List.of("*"));
                    configuration.setAllowedHeaders(List.of("*"));
                    return configuration;
                });
        http.csrf().disable();
        return http.build();
    }
}
gg0vcinb

gg0vcinb5#

Tr1monster的答案有效,可能是最好的方法。
Java配置的一个稍微紧凑的版本:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
public class CorsConfig 
    extends CorsConfiguration
{
    @Bean
    public CorsWebFilter corsFilter()
    {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials( true );
        config.setAllowedOrigins( List.of( "*" ) );
        config.setAllowedMethods( List.of( "GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD" ) );
        config.setAllowedHeaders( List.of( "origin", "content-type", "accept", "authorization", "cookie" ) );

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration( "/**", config );

        return new CorsWebFilter( source );
    }
}

相关问题