Spring Boot – CORS Support

Cross-Origin Resource Sharing (CORS) is a security concept that allows restricting the resources implemented in web browsers. It prevents the JavaScript code producing or consuming the requests against different origin.

For example, your web application is running on 8080 port and by using JavaScript you are trying to consuming RESTful web services from 9090 port. Under such situations, you will face the Cross-Origin Resource Sharing security issue on your web browsers.

Two requirements are needed to handle this issue −

  • RESTful web services should support the Cross-Origin Resource Sharing.
  • RESTful web service application should allow accessing the API(s) from the 8080 port.

In this chapter, we are going to learn in detail about How to Enable Cross-Origin Requests for a RESTful Web Service application.

Enable CORS in Controller Method

We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.

@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")

public ResponseEntity<Object> getProduct() {
   return null;
}

Global CORS Configuration

We need to define the shown @Bean configuration to set the CORS configuration support globally to your Spring Boot application.

@Bean
public WebMvcConfigurer corsConfigurer() {
   return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
         registry.addMapping("/products").allowedOrigins("http://localhost:9000");
      }    
   };
}

To code to set the CORS configuration globally in main Spring Boot application is given below.

package com.maixuanviet.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
   @Bean
   public WebMvcConfigurer corsConfigurer() {
      return new WebMvcConfigurerAdapter() {
         @Override
         public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/products").allowedOrigins("http://localhost:8080");
         }
      };
   }
}

Now, you can create a Spring Boot web application that runs on 8080 port and your RESTful web service application that can run on the 9090 port. For further details about implementation about RESTful Web Service, you can refer to the chapter titled Consuming RESTful Web Services of this tutorial.

Related posts:

Ignore Null Fields with Jackson
Map Interface trong java
Auditing with JPA, Hibernate, and Spring Data JPA
Java Program to Create a Balanced Binary Tree of the Incoming Data
Java Program to Implement Stack
Java Program to Perform Uniform Binary Search
@Order in Spring
Adding Parameters to HttpClient Requests
Giới thiệu java.io.tmpdir
Documenting a Spring REST API Using OpenAPI 3.0
Java Program to Perform Preorder Non-Recursive Traversal of a Given Binary Tree
Inject Parameters into JUnit Jupiter Unit Tests
Java Program to implement Circular Buffer
Java Program to Implement Hamiltonian Cycle Algorithm
Spring REST API + OAuth2 + Angular
Lớp Arrarys trong Java (Arrays Utility Class)
Tính đa hình (Polymorphism) trong Java
Java Program to Find k Numbers Closest to Median of S, Where S is a Set of n Numbers
Java Program to Implement Strassen Algorithm
Java Program to Perform Insertion in a 2 Dimension K-D Tree
Java Program to Implement D-ary-Heap
Properties with Spring and Spring Boot
How to Remove the Last Character of a String?
The Dining Philosophers Problem in Java
Java 8 Predicate Chain
Java Program to Implement Hash Tables Chaining with List Heads
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Java Program to Create a Random Linear Extension for a DAG
Java Program to Implement Traveling Salesman Problem using Nearest neighbour Algorithm
Java Program to Construct an Expression Tree for an Infix Expression
Apache Commons Collections OrderedMap
How to Find an Element in a List with Java