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

8

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)

Parabola answered 13/4, 2020 at 14:15 Comment(3)
can you share your pom.xml ?Lionhearted
I added the pom.xml. I also added the repo for if you need to see more filesParabola
Would you min helping here: #73357627Denticle
L
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);
    }  
}
Lionhearted answered 13/4, 2020 at 14:39 Comment(16)
Where do I need to put this CrosWebFilter? Do I need to create a CustomCorsConfigration class (because it doesnt exist) and the return CrosWebFilter expects a CorsConfigurationSource but a UrlBasedCorsConfigurationSource is used hereParabola
What version of spring cloud gateway you are using ?Lionhearted
I use the spring boot version 2.2.6Parabola
And in the pom.xml i see that I use 0.0.1 -snapshot for the cloud gateway. I created this project 2 days ago so I would think I have the latest versionParabola
If you copy in your project this code snippet do you have compilation errors?Lionhearted
Yes, CustomCorsConfiguration doesn't exist and the corsConfig in source.registerCorsConfiguration expects a CorsConfiguration instead of a CustomCorsConfigurationParabola
Sorry , one momentLionhearted
Update ,please tryLionhearted
The errors are gone, and the error is now a bit different imgur.com/a/N0PNzmH. I'll also update my postParabola
Can you please remove global cors configuration from yml ?Lionhearted
Also please remove @CrossOrigin(origins = "*")Lionhearted
Do you have cors config in another microservices?Lionhearted
Yes, I didn't think this would be a problem. I also used @CrossOrigins in my other services. When I removed those it all worked. Thank you for everything, you saved me allot of time!Parabola
Thank you guys for this, I tried some many things that didn't work until I saw this. Thanks once againTriclinic
Would you min helping here: #73357627Denticle
How it works for you. With the latest version of Spring Gateway, only reactive dependencies are available. org.springframework.web.course.reactive.CorsWebFilter. And there are no such properties.Housman
D
25

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
          ...
Damage answered 11/5, 2021 at 11:48 Comment(7)
for some reason 'default-filters' was key for me, wonder why the spring docs doesn't include this in their examplePolley
Absolutly works for me. Thanks @Malte bro.Sula
Ditto on the default filters being needed, but I only needed to add the Access-Control-Allow-OriginStalinsk
Would you min helping here: #73357627Denticle
absolutely this is working well. thanks a lot.Stegodon
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: <some host based on request origin added in the code> and Access-Control-Allow-Origin: "*"Murillo
worked very smoothly, took me around 1 day to find this solution.Dulaney
L
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);
    }  
}
Lionhearted answered 13/4, 2020 at 14:39 Comment(16)
Where do I need to put this CrosWebFilter? Do I need to create a CustomCorsConfigration class (because it doesnt exist) and the return CrosWebFilter expects a CorsConfigurationSource but a UrlBasedCorsConfigurationSource is used hereParabola
What version of spring cloud gateway you are using ?Lionhearted
I use the spring boot version 2.2.6Parabola
And in the pom.xml i see that I use 0.0.1 -snapshot for the cloud gateway. I created this project 2 days ago so I would think I have the latest versionParabola
If you copy in your project this code snippet do you have compilation errors?Lionhearted
Yes, CustomCorsConfiguration doesn't exist and the corsConfig in source.registerCorsConfiguration expects a CorsConfiguration instead of a CustomCorsConfigurationParabola
Sorry , one momentLionhearted
Update ,please tryLionhearted
The errors are gone, and the error is now a bit different imgur.com/a/N0PNzmH. I'll also update my postParabola
Can you please remove global cors configuration from yml ?Lionhearted
Also please remove @CrossOrigin(origins = "*")Lionhearted
Do you have cors config in another microservices?Lionhearted
Yes, I didn't think this would be a problem. I also used @CrossOrigins in my other services. When I removed those it all worked. Thank you for everything, you saved me allot of time!Parabola
Thank you guys for this, I tried some many things that didn't work until I saw this. Thanks once againTriclinic
Would you min helping here: #73357627Denticle
How it works for you. With the latest version of Spring Gateway, only reactive dependencies are available. org.springframework.web.course.reactive.CorsWebFilter. And there are no such properties.Housman
D
3

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, *
Demodulation answered 20/9, 2022 at 18:9 Comment(0)
C
3

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: "*"
Copyright answered 12/10, 2022 at 13:19 Comment(0)
L
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
Lated answered 24/7, 2022 at 3:1 Comment(1)
Would you min helping here: #73357627Denticle
V
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);
}
Veradia answered 11/1, 2023 at 12:55 Comment(0)
S
-1

maybe you need to set "allowCredentials"

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "https://example.com"
            allowCredentials: true
            allowedMethods:
            - GET
            - POST
Sycosis answered 26/5, 2021 at 9:11 Comment(1)
Strangely not working for meDenticle
H
-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.

Hypoploid answered 9/1, 2021 at 11:35 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.