How to configure CORS in Spring Boot

Configure CORS in a Spring Boot REST application to make it accessible from a frontend application such as React or Angular. 1. What i...

Configure CORS in a Spring Boot REST application to make it accessible from a frontend application such as React or Angular.

1. What is CORS and why do we need CORS?

CORS or Cross-Origin Resource Sharing is a browser security feature that restricts accessing the resource of server b from an HTTP request initiated by a script coming from server a.

Normally, we have our API server running on the backend such as This is where actual data fetching and manipulation happens.

On the other side, we have our frontend client which is normally powered by either React, Angular, or Vue. For example, And this client fetches data from our API server.

1.1 How CORS work?

This is a sequence diagram when calling GET /books endpoint.
  1. Perform a CORS preflight request.
  2. If CORS headers from the server match the client, proceed. Otherwise, throw a CORS error.
  3. Return response with data.

2. Different Ways of Configuring CORS

2.1 CrossOrigin Annotation

CrossOrigin is a Spring annotation that we can use on any Java type or method to configure CORS.
This is good if you just have one or two endpoints.

I normally use it to override the global configuration when testing a particular endpoint.

2.2 Globally via Spring WebMvcConfigurer

In practice, we would normally use this approach as often we have a defined set of clients who will access the resource server in the same way. And having the configuration in the same place makes maintenance easier.

Here's an example configuration:
package com.czetsuyatech.core.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

public class WebMvcConfig implements WebMvcConfigurer {

  public void addCorsMappings(CorsRegistry registry) {
  • "*" means it will accept any allowable value for that field. For example, allowedMethods will accept GET, POST, PUT, DELETE, OPTIONS, etc. @see org.springframework.http.HttpMethod.
  • allowedOrigins, tells Spring to only accept Ajax requests from these URL patterns.
  • maxAge - indicates how long to cache the result of a CORS preflight request.

3. Deployment and Testing

To see how CORS work, clone the following GIT repositories:

3.1 Requirements

You must have the following components installed on your local machine:
  • OpenJDK 11 -
  • Node -
  • Yarn - in a terminal execute, npm install --global yarn
In the root of the spring-cors project execute: mvn spring-boot:run

In the root of spring-cors-nextjs project execute: yarn install && yarn dev 

4. References


coding 3754133847944964812

Post a Comment Default Comments