19

I have a Angular frontend, spring cloud gateway and a spring web service. When I try to send GET/POST data to the spring web service through the gateway I get the following error: CORS error. When sending the data directly to the web service it works fine so I think the problem is in the gateway.

In the gateway I have to following files:

@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();
    }

}

application.properties: I thought the server: cloud: etc etc.. would do the trick but no

server.port=8080

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

Pom.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>

CorsConfiguration File:

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);
}

Gateway Repo: https://github.com/KylevanRaaij/Gateway

Service to connect to: https://github.com/KylevanRaaij/UserService (this one works when connecting direct) (for example my angular project)

Kyle Van Raay
  • 228
  • 1
  • 2
  • 11

8 Answers8

23

Spring documentation tells its enough to declare such configuration in application.yml

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

Also you can define your custom 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);
    }  
}
Mykhailo Moskura
  • 2,073
  • 1
  • 9
  • 20
23

This Way it worked for me:

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
          ...
Malte Svenson
  • 231
  • 2
  • 2
  • 1
    for some reason 'default-filters' was key for me, wonder why the spring docs doesn't include this in their example – sbnarra Dec 19 '21 at 18:26
  • Absolutly works for me. Thanks @Malte bro. – Daniel Rch. Dec 25 '21 at 05:39
  • Ditto on the `default filters` being needed, but I only needed to add the `Access-Control-Allow-Origin` – RobOhRob Jun 03 '22 at 19:27
  • Would you min helping here: https://stackoverflow.com/questions/73357127/spring-cloud-apigw-spring-boot-and-openapi-issue-cors-issue – PAA Aug 15 '22 at 06:30
  • absolutely this is working well. thanks a lot. – Mafei Aug 21 '22 at 22:31
  • Did the job! Thank you. In my case, I have a SecurityWebFilterChain config that copes with cors (spring security) and I have noticed that I am getting two response headers of Access-Control-Allow-Origin: Access-Control-Allow-Origin: and Access-Control-Allow-Origin: "*" – recies Dec 23 '22 at 22:02
2

Based on this Github issue, by adding this worked for me:

spring:
  cloud:
    gateway:
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
        - AddResponseHeader=Access-Control-Allow-Origin, *
Enfield Li
  • 1,952
  • 1
  • 8
  • 23
1

This worked for me (SPRING & ANGULAR):

Define CorsConfiguration

  @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);
    }}
 

Define application.yml

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: 'http://localhost:4200'
            allowedHeaders:
              - Content-Type
            allowedMethods:
              - GET
              - POST
              - PUT
              - DELETE
Italo Oré
  • 67
  • 4
  • Would you min helping here: https://stackoverflow.com/questions/73357127/spring-cloud-apigw-spring-boot-and-openapi-issue-cors-issue – PAA Aug 15 '22 at 06:31
0

The blow solution is worked for me. As we are routing through gateway we need to configure CROS in yaml or properties file.

<div>
spring:
  cloud:
    gateway:
      default-filters:
      - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
      globalcors:
        cors-configurations:
          '[/**]':
           allowedOrigins: "*"
           allowedMethods: "*"
           allowedHeaders: "*"
Sakthi
  • 1
  • 3
0
@Bean
public CorsFilter corsFilter() {
  final UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
  final CorsConfiguration config=new CorsConfiguration();
  config.setAllowCredentials(true);
  config.addAllowedHeader("*");
  config.addAllowedOriginPattern("*");
  config.addAllowedMethod("OPTIONS");
  config.addAllowedMethod("POST");
  config.addAllowedMethod("GET");
  config.addAllowedMethod("PUT");
  config.addAllowedMethod("DELETE");
  source.registerCorsConfiguration("/**", config);
  return new CorsFilter(source);
}
willome
  • 3,062
  • 19
  • 32
-1

maybe you need to set "allowCredentials"

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "https://example.com"
            allowCredentials: true
            allowedMethods:
            - GET
            - POST
hdsuperman
  • 182
  • 2
  • 6
-5

That problem appears when you add yml file then pom.xml file will be red, You have to delete m2/repository and build your project again, After that pom.xml is normal and the problem will be solved.

max
  • 1
  • 1