Spring Web关请求被CORS阻止(无Access 0 Control-Allow-Orgin标题)

9njqaruj  于 2023-01-12  发布在  Spring
关注(0)|答案(8)|浏览(135)

我有一个Angular前端spring云网关和一个spring Web服务。当我尝试通过网关向spring Web服务发送GET/POST数据时,我收到以下错误:CORS error.当直接将数据发送到Web服务时,它工作正常,所以我认为问题出在网关上。
在网关中,我必须以下文件:

@Configuration
@CrossOrigin(origins = "*")
public class SpringCloudConfig {

    @Bean
    public RouteLocator gatewayRoutes(RouteLocatorBuilder builder){
        return builder.routes()
                .route(r -> r.path("/users/**")
                .uri("http://localhost:8081/")
                .id("userService"))

                .route(r -> r.path("/posts/**")
                        .uri("http://localhost:8082/")
                        .id("postService"))

                .route(r -> r.path("/auth/**")
                        .uri("http://localhost:8083/")
                        .id("securityService"))
                .build();
    }

}

**应用程序.属性:**我以为服务器:云:等等等等。会做的伎俩,但没有

server.port=8080

spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "*"
allowedMethods:
- GET
- POST

聚合物.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.cloudGateway</groupId>
<artifactId>gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>gateway</name>
<description>Gateway project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Cors配置文件:

package com.cloudGateway.gateway;

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

import java.util.Arrays;
import java.util.Collections;

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

    @Bean
    public CorsWebFilter corsWebFilter() {

    final CorsConfiguration corsConfig = new CorsConfiguration();
    corsConfig.setAllowedOrigins(Collections.singletonList("*"));
    corsConfig.setMaxAge(3600L);
    corsConfig.setAllowedMethods(Arrays.asList("GET", "POST"));
    corsConfig.addAllowedHeader("*");

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

    return new CorsWebFilter(source);
}

网关回购协议:https://github.com/KylevanRaaij/Gateway
要连接到的服务:https://github.com/KylevanRaaij/UserService(此服务在直接连接时可用)(例如我的Angular 项目)

pcrecxhr

pcrecxhr1#

也许您需要设置“allowCredentials”

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "https://example.com"
            allowCredentials: true
            allowedMethods:
            - GET
            - POST
368yc8dk

368yc8dk2#

这个问题出现时,你添加yml文件然后pom.xml文件将是红色的,你必须删除m2/repository并重新构建您的项目,之后pom.xml是正常的,问题将得到解决。

uelo1irk

uelo1irk3#

Spring文档告诉它在application.yml中声明这样的配置就足够了

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods:
            - GET
            - POST

您还可以定义自定义CorsConfiguration:

@Configuration
public class CorsConfiguration{
    @Bean
    public CorsWebFilter corsWebFilter() {

        final CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.setAllowedOrigins(Collections.singletonList("*"));
        corsConfig.setMaxAge(3600L);
        corsConfig.setAllowedMethods(Arrays.asList("GET", "POST"));
        corsConfig.addAllowedHeader("*");

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

        return new CorsWebFilter(source);
    }  
}
igsr9ssn

igsr9ssn4#

这对我很有效:

spring:
  application:
    name: API-GATEWAY
  cloud:
    gateway:
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
      globalcors:
        corsConfigurations:
          '[/**]':
              allowedOrigins: "*"
              allowedMethods: "*"
              allowedHeaders: "*"
      routes:
        - id: USER-SERVICE
          uri: lb://USER-SERVICE
          ...
vs91vp4v

vs91vp4v5#

这对我很有效(Spring和Angular ):
定义相关配置

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

    @Bean
    public CorsWebFilter corsWebFilter() {

        final CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));
        corsConfig.setMaxAge(3600L);
        corsConfig.setAllowedMethods(Arrays.asList("GET", "POST","PUT", "DELETE"));
        corsConfig.addAllowedHeader("Content-Type");

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

        return new CorsWebFilter(source);
    }}

定义应用程序.yml

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: 'http://localhost:4200'
            allowedHeaders:
              - Content-Type
            allowedMethods:
              - GET
              - POST
              - PUT
              - DELETE
ss2ws0br

ss2ws0br6#

基于Github的这个问题,我添加了以下内容:

spring:
  cloud:
    gateway:
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
        - AddResponseHeader=Access-Control-Allow-Origin, *
flvlnr44

flvlnr447#

打击解决方案是为我工作。因为我们是通过网关路由,我们需要在yaml或属性文件配置CROS。

<div>
spring:
  cloud:
    gateway:
      default-filters:
      - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
      globalcors:
        cors-configurations:
          '[/**]':
           allowedOrigins: "*"
           allowedMethods: "*"
           allowedHeaders: "*"
pepwfjgg

pepwfjgg8#

@Bean公共关联过滤器关联过滤器(){最终的基于关联的URL配置源源=新的基于关联的URL配置源();最终相关配置配置=新相关配置();配置设置允许凭证(true);配置添加允许标头(“”);配置添加允许的原始模式(“”);配置添加允许方法(“选项”);配置添加允许方法(“POST”);配置添加允许方法(“GET”);配置添加允许方法(“PUT”);配置添加允许方法(“删除”);配置(“/**",配置);返回新的CorsFilter(源代码);}

相关问题