1. Overview

Cross-Origin Resource Sharing (CORS) is a security mechanism for browser-based applications that allows a web page from one domain to access another domain’s resources. The browser implements the same-origin access policy to restrict any cross-origin application access.

Also, Spring provides first-class support for easily configuring CORS in any Spring, Spring Boot web, and Spring Cloud gateway application.

In this article, we’ll learn how to set up a Spring Cloud Gateway application with a backend API. Also, we’ll access the gateway API and debug a common CORS-related error.

Then, we’ll configure the Spring gateway API with Spring CORS support.

2. Implement the API Gateway With Spring Cloud Gateway

Let’s imagine we need to build a Spring Cloud gateway service to expose a backend REST API.

2.1. Implement the Backend REST API

Our backend application will have an endpoint to return User data.

First, let’s model the User class:

public class User {
    private long id;
    private String name;

    //standard getters and setters
}

Next, we’ll implement the UserController with the getUser endpoint:

@GetMapping(path = "/user/{id}")
public User getUser(@PathVariable("id") long userId) {
    LOGGER.info("Getting user details for user Id {}", userId);
    return userMap.get(userId);
}

2.2. Implement the Spring Cloud Gateway Service

Now let’s implement an API gateway service using the Spring Cloud Gateway support.

First, we’ll include the spring-cloud-starter-gateway dependency:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
    <version>4.1.5</version
</dependency>

2.3. Configure the API Routing

We can expose the User service endpoint using the Spring Cloud Gateway routing option.

We’ll configure the predicates with the /user path and set the uri property with the backend URI http://::

spring:
  cloud:
    gateway:
      routes:
        -  id: user_service_route
           predicates:
             - Path=/user/**
           uri: http://localhost:8081

3. Test the Spring Gateway API

Now we’ll test the Spring gateway service from the terminal with a cURL command and the browser window.

3.1. Testing the Gateway API With cURL

Let’s run both services, User and Gateway:

$ java -jar ./spring-backend-service/target/spring-backend-service-1.0.0-SNAPSHOT.jar
$ java -jar ./spring-cloud-gateway-service/target/spring-cloud-gateway-service-1.0.0-SNAPSHOT.jar

Now, let’s access the /user endpoint using the gateway service URL:

$ curl -v 'http://localhost:8080/user/100001'
< HTTP/1.1 200 OK
< Content-Type: application/json
{"id":100001,"name":"User1"}

As tested above, we’re able to get the backend API response.

3.2. Testing With the Browser Console

To experiment in a browser environment, we’ll open our frontend application e.g. https://www.baeldung.com, and use the browser’s supported developer tools option.

We’ll use the Javascript fetch function to call the API from a different origin URL:

fetch("http://localhost:8080/user/100001")

CORS_ERROR

As we can see from the above, the API request failed due to the CORS error.

We’ll further debug the API request from the browser’s network tab:

OPTIONS /user/100001 HTTP/1.1
Access-Control-Request-Method: GET
Access-Control-Request-Private-Network: true
Connection: keep-alive
Host: localhost:8080
Origin: https://www.baeldung.com

Also, let’s verify the API response:

HTTP/1.1 403 Forbidden
...
content-length: 0

The above request failed because the web page URL’s scheme*,* domain, and port are different than the gateway API’s. The browser expects the Access-Control-Allow-Origin header to be included by the server, but instead gets an error.

By default, the Spring returns a Forbidden 403 error on the preflight OPTIONS request as the origin is different.

Next, we’ll fix the error by using the Spring Cloud gateway’s supported CORS configuration.

4. Configure CORS Policy in API Gateway

We’ll now configure the CORS policy to allow a different origin to access the gateway API.

Let’s configure the CORS access policy using the globalcors properties:

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "https://www.baeldung.com"
            allowedMethods:
              - GET
            allowedHeaders: "*"

We should note that the globalcors properties would apply the CORS policy to all routing endpoints*.*

Alternatively, we can configure the CORS policy per API route:

spring:
  cloud:
    gateway:
      routes:
        -  id: user_service_route
           ....
           metadata:
             cors:
               allowedOrigins: 'https://www.baeldung.com,http://localhost:3000'
               allowedMethods:
                 - GET
                 - POST
               allowedHeaders: '*'

The allowedOrigins field can be configured as a specific domain name, or comma-separated domain names, or set as the * wildcard character to allow any cross-origin. Similarly, the allowedMethods and allowedHeaders properties can be configured with specific values or with the * wildcard.

Also, we can use an alternative allowedOriginsPattern configuration to provide more flexibility with the cross-origin pattern matching:

allowedOriginPatterns:
  - https://*.example1.com
  - https://www.example2.com:[8080,8081]
  - https://www.example3.com:[*]

In contrast to the allowedOrigins property, the allowedOriginsPattern allows the * wildcard character in any part of the URL including the scheme, domain name, and port number for pattern matching. In addition, we can specify the comma-separated port numbers within a bracket. However, the allowedOriginsPattern property does not support any regular expression.

Now, let’s re-verify the user API in the browser’s console window:

CORS_SUCCESS

We’re now getting a HTTP 200 response from the API gateway.

Also, let’s confirm the Access-Control-Allow-Origin header in the OPTIONS API response:

HTTP/1.1 200 OK
...
Access-Control-Allow-Origin: https://www.baeldung.com
Access-Control-Allow-Methods: GET
content-length: 0

We should note that it’s recommended to configure a finite set of allowed origins to provide the highest level of security.

By default, the CORS specs don’t allow any cookie or CSRF token in any cross-origin request. However, we can enable it using the allowedCredentials property set as true. Also, the allowedCredentials do not work when used with the * wildcard in the allowedOrigins and allowedHeaders properties*.*

5. Conclusion

In this article, we’ve learned how to implement a Gateway service using the Spring Cloud gateway support. We’ve also encountered a usual CORS error while testing the API from a browser console.

Finally, we’ve demonstrated how to fix the CORS error by configuring the application with the allowedOrigins, and allowedMethods properties.

As always, the example code can be found over on GitHub.