Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 696
Kyle Van Raay Avatar asked Apr 13 '20 14:04

Kyle Van Raay


People also ask

How do I enable CORS in API gateway Spring boot?

The way to allow only specific origin in Spring boot application. Usually, the only thing you have to do in case of simple spring boot application is to add @CrossOrigin annotation to specific controller or method of the controller (you can have really granular control over requests).

How do I enable CORS in Spring Security?

Enabling CORS Configuration Globally in Spring Webflux To define CORS globally in a Spring Webflux application, we use the WebfluxConfigurer and override the addCorsMappings() . Similar to Spring MVC, it uses a CorsConfiguration with defaults that can be overridden as required.

Is CORS enabled by default in Spring boot?

No. You need to add @CrossOrigin annotation by yourself to get CORS Support in Spring. Why: Enabling CORS (Cross-origin resource sharing) by default will be a serious security issue.

Which elements are used to build a routing rule in Spring Cloud Gateway?

It is defined by an ID, a destination URI, a collection of predicates and a collection of filters. A route is matched if aggregate predicate is true.


1 Answers

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);
    }  
}
like image 120
Mykhailo Moskura Avatar answered Oct 13 '22 18:10

Mykhailo Moskura