Spring Boot – CORS Support using Java Config

In previous post, we have created a REST Service with Spring CORS integration using @CrossOrigin. This tutorial will introduce way to define global CORS configuration out of our Controller with Java Config in Spring Boot example.

Related Articles:
Spring CORS example using @CrossOrigin – Spring Boot
Spring Boot – CORS Support using XML Config
AngularJs CrossSite HTTP Requests to SpringBoot RestAPIs

I. Global CORS Configuration using Java Config

Spring provides a way that uses Java Config applying for all REST Service Controllers in our project.
WebMvcConfigurerAdapter has addCorsMappings() method that we need to override to configure CORS:

@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {

	@Override
	public void addCorsMappings(CorsRegistry registry) {

		registry.addMapping("/customers")
				.allowedOrigins("http://localhost:8484", "http://localhost:9000")
				.allowedMethods("POST", "GET", "PUT", "DELETE")
				.allowedHeaders("Content-Type")
				.exposedHeaders("header-1", "header-2")
				.allowCredentials(false)
				.maxAge(6000);

	}
}

allowedOrigins(): specifies the URI that can be accessed by resource. “*” means that all origins are allowed. If undefined, all origins are allowed.

allowCredentials(): defines the value for Access-Control-Allow-Credentials response header. If value is true, response to the request can be exposed to the page. The credentials are cookies, authorization headers or TLS client certificates. The default value is true.

maxAge(): defines maximum age (in seconds) for cache to be alive for a pre-flight request. By default, its value is 1800 seconds.

allowedMethods(): specifies methods (GET, POST,…) to allow when accessing the resource. If we don’t use this attribute, it takes the value of @RequestMapping method by default. If we specify methods, default method will be overridden.

allowedHeaders(): defines the values for Access-Control-Allow-Headers response header. We don’t need to list headers if it is one of Cache-Control, Content-Language, Expires, Last-Modified, or Pragma. By default all requested headers are allowed.

exposedHeaders(): values for Access-Control-Expose-Headers response header. Server uses it to tell the browser about its whitelist headers. By default, an empty exposed header list is used.

II. Practice

1. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.4.RELEASE
– Spring Boot: 1.5.4.RELEASE

2. Project Overview

spring-cors-javaconfig-structure

Dependency for Spring Boot Starter Web in pom.xml.

3. Step by step
3.1 Create Spring Boot project

Using Spring Tool Suite/Eclipse to create Project and add Dependencies to pom.xml file:


	org.springframework.boot
	spring-boot-starter-web

3.2 Create Data Model Classes
package com.javasampleapproach.corsjavaconfig.model;

public class Customer {

	private Long id;
	private String name;

	public Customer(Long id, String name) {
		this.id = id;
		this.name = name;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
3.3 Create Service
package com.javasampleapproach.corsjavaconfig.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.javasampleapproach.corsjavaconfig.model.Customer;

@Service
public class CustomerService {

	public List getCustomers() {

		List list = new ArrayList<>();
		list.add(new Customer(1L, "Jack"));
		list.add(new Customer(2L, "Adam"));
		list.add(new Customer(3L, "Kim"));

		return list;
	}
}
3.4 Create Controller
package com.javasampleapproach.corsjavaconfig.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javasampleapproach.corsjavaconfig.model.Customer;
import com.javasampleapproach.corsjavaconfig.service.CustomerService;

@RestController
public class WebController {

	@Autowired
	private CustomerService service;

	@RequestMapping("customers")
	public List getCustomers() {

		List list = service.getCustomers();
		return list;
	}

	@RequestMapping("data")
	public List getData() {

		List list = service.getCustomers();
		list.forEach(item -> item.setName(item.getName().toUpperCase()));

		return list;
	}
}
3.5 Create Configuration Class
package com.javasampleapproach.corsjavaconfig.config;

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

@Configuration
@ComponentScan("com.javasampleapproach.corsjavaconfig")
public class AppConfig extends WebMvcConfigurerAdapter {

	@Override
	public void addCorsMappings(CorsRegistry registry) {

		registry.addMapping("/customers")
				.allowedOrigins("http://localhost:8484", "http://localhost:9000")
				.allowedMethods("POST", "GET", "PUT", "DELETE")
				.allowedHeaders("Content-Type")
				.exposedHeaders("header-1", "header-2")
				.allowCredentials(false)
				.maxAge(6000);

	}
}
3.6 Run & Check Result

– Config maven build:
clean install
– Run project with mode Spring Boot App and port 8080.
– Create Client Application (stored in folder webapps/Cors of Apache Tomcat):

$(document).ready(function() {
	$.ajax({
		url: "http://localhost:8080/customers"
	}).then(function(data) {
	  var items = [];
	  $.each( data, function( key, val ) {
		items.push("Id: "+val.id +", Name: "+val.name+"
"); }); $('.result').append(items); }); });


    
        Spring Boot - CORS%MINIFYHTMLee8dfe8374d7916c5a4b5cf8a06f69af16%%MINIFYHTMLee8dfe8374d7916c5a4b5cf8a06f69af17%
    
        
%MINIFYHTMLee8dfe8374d7916c5a4b5cf8a06f69af18%

– Deploy client project on Tomcat with port 8484:

Send Request on Browser:
http://localhost:8484/Cors/index.html
Result:

Id: 1, Name: Jack
Id: 2, Name: Adam
Id: 3, Name: Kim

Clear Browser Cache, then modify data.js file by changing url to:

$.ajax({
	url: "http://localhost:8080/data"
})

Send Request on Browser:
http://localhost:8484/Cors/index.html
Result: Browser shows nothing.

III. Source Code

SpringBootCORSJavaConfig
Cors



By grokonez | June 12, 2017.

Last updated on October 31, 2017.



Related Posts


1 thought on “Spring Boot – CORS Support using Java Config”

  1. Everyone can do it with Get, and it is written everywhere.

    What is about POST???
    or
    PUT???
    can you show how?
    Thank you,
    Andre Morua

Got Something To Say:

Your email address will not be published. Required fields are marked *

*