Issue
I am trying to build Gateway proxy using Spring Cloud Gateway.
I am able to route my requests to respective services using RouteLocator in Spring Cloud. But I am not able to configure CORS for the paths which are routing through RouteLocator.
I tried all the possibilities which are mentioned in the Spring Cloud document.
I am facing following error in my webpage:
My code looks like Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
// tag::route-locator[]
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(p -> p
.path("/order/**")
.filters(f -> f.setResponseHeader("Access-Control-Allow-Origin", "http://localhost:8081")
)
.uri("http://localhost:9090"))
.route(p -> p
.path("/priority-model/selection/**")
.filters(f -> f.addResponseHeader("Access-Control-Allow-Origin", "http://localhost:8081")
)
.uri("http://localhost:9090"))
.build();
}
}
application.yml
server:
port: 8080
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "*"
allowedMethods:
- GET
buils.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.5.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
bootJar {
baseName = 'gs-gateway'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Finchley.SR2"
}
}
dependencies {
compile("org.springframework.cloud:spring-cloud-starter-gateway")
compile("org.springframework.cloud:spring-cloud-starter-netflix-hystrix")
compile("org.springframework.cloud:spring-cloud-starter-contract-stub-runner"){
exclude group: "org.springframework.boot", module: "spring-boot-starter-web"
}
compile group: 'org.springframework.cloud', name: 'spring-cloud-gateway-webflux', version: '2.0.2.RELEASE'
testCompile("org.springframework.boot:spring-boot-starter-test")
}
Solution
By default, API Gateway enables CORS for all the origins, if you want to allow only whitelisted origins then use globalcors configurations.
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "*"
allowedMethods:
- GET
Answered By - samba