SpringBoot CORS Support

Technology: CORS (cross origin Resource Sharing) allows the webapge to request the resources into browser from multiple domains. In general browser will throw warning, if the request from one domain is requesting to another domain. Spring provides CORS @CrossOrigin annotation, allows the specified/all origins, and different request methods, and based on header etc…

@CrossOrigin has the different attributes, we will explore all these attributes with its usage.

Attribute

Description

origins

List of all allowed origin from different domains, it will add Access-Control-Allow-Origin header to the request.

If specify either * or no value is specified means it will allow all domains.

allowedHeaders

List of request Headers that are permitted in a actual request, if we are not specified or * means allow all headers. The Default allowed headers are:

  1. Cache-control

  2. Content-Language

  3. Expires

  4. LAst-Modified

  5. Pragma

exposeHeaders

List of response headers that user-agent will allow the client on actual response other than simple Headers.

  1. Cache-control

  2. Content-Language

  3. Expires

  4. LAst-Modified

  5. Pragma

methods

List of HTTP request methods, by default all controller request methods will allow.

allowCredentials

Whether browser should send credentials such as cookies along with cross domain request to annotated endpoint or not. The value is set on cookie “Access-Control-Allow-Credentials” header.

maxAge

Maximum age in seconds of the cache response of preflight requests. Setting this to reasonable value will decrease the interactions required by browser. It will set the value to “Access-Control-Max-Age” cookie. If we specify any negative value means undefined, the default value is 1800 seconds.

@CrossOrigin Target is either TYPE or METHOD, means either we can specify at the class level or at the method level.

Configuring the Cross Origin configuration.

1) We can specify the Cross Origin Configuration at each controller level.

Example:

@RestController
@CrossOrigin
public class CrossOriginController {
	@GetMapping("cross")
	public Sample getCORSExample1() {
		return new Sample("CORS", "Example");
	}
	
	@CrossOrigin(origins="http://localhost:8081")
	@GetMapping(value="cross2")
	public Sample getCORSExample2() {
		return new Sample("CORS2", "Example2");
	}
}

If we specify the class level and method level, based on attribute type, it will be merged or overwrite. If the attribute type is array then it will be merged otherwise it will be overwritten.

2) Configuring CORS at Global level.

We can create a bean of the type “CorsConfigurationSource” and provide the configuration related to CORS. So that it will be applicable for all spring controllers.

@Bean
CorsConfigurationSource corsConfigurationSource()
{
	CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
	configuration.setAllowedMethods(Arrays.asList("GET","POST"));
	UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
	source.registerCorsConfiguration("/**", configuration);
	return source;
}

3) Another way to specify the configuration global level.

Create a class extends “WebMvcConfigurerAdapter” and override the CORS mapping method and provide the implementation.

@Override
	public void addCorsMappings(CorsRegistry registry) {
	}

Or we can implement the “WebMvcConfigurer” interface and override the method corsMapping method, if we can using java version >=8.

@Configuration
@EnableWebMvc
public class CorsConfiguration implements  WebMvcConfigurer {
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		// provide the implementation
	}
}

If we are using XML file for configuration then we can use mvc namespace for configuring the CORS.

<mvc:cors>
 
    <mvc:mapping path="/api/**"
        allowed-origins="http://domain1.com, http://domain2.com"
        allowed-methods="GET, PUT"
        allowed-headers="header1, header2, header3"
        exposed-headers="header1, header2" allow-credentials="false"
        max-age="123" />
    <mvc:mapping path="/resources/**"
        allowed-origins="http://domain1.com" />
</mvc:cors> 

How It Works:

To understand the request flow, first we need to understand what is preflight request.

Browser will two types of requests, simple request and preflight request.

Preflight Requests:

Some request we can call as simple, it don’t trigger preflight request. For example if browser will only allow HTTP methods like GET, POST, and HEAD.

Simple Request:

If the request method is browser supported method then we can say it is a Simple request.

For each request Spring MVC will check for CORS request, usinf AbstractHAndlerMapping getHandler method, if it is CORS Request (preflight and Simple), if it is preflight request it will execute the CORS execution chain , and if it is Simple CORS request it will add CorsInterceptor to the chain to add the required headers.

Conclusion: We understood the what is CORS Request, how to allow different domain origin to access our application. We learned how to configure CORS at the controller level and application level.

Java development team also describe the preflight requests and Request flow of the CORS request for build in your Java development.

Leave a Reply

Your email address will not be published.




*

code