Kyle Van Raay
Kyle Van Raay

Reputation: 248

Spring Gateway Request blocked by CORS (No Acces0Control-Allow-Orgin header)

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)

Upvotes: 19

Views: 36581

Answers (8)

Mohammad Javed
Mohammad Javed

Reputation: 1

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

Upvotes: 0

Sakthi
Sakthi

Reputation: 31

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: "*"

Upvotes: 3

Enfield Li
Enfield Li

Reputation: 2530

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, *

Upvotes: 3

Italo Or&#233;
Italo Or&#233;

Reputation: 65

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

Upvotes: 1

hdsuperman
hdsuperman

Reputation: 452

maybe you need to set "allowCredentials"

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

Upvotes: -1

Malte Svenson
Malte Svenson

Reputation: 251

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

Upvotes: 25

max
max

Reputation: 1

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.

Upvotes: -5

Mykhailo Moskura
Mykhailo Moskura

Reputation: 2211

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

Upvotes: 24

Related Questions