Course – LS (cat=Spring)

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

>> LEARN SPRING

1. Overview

In any modern browser, Cross-Origin Resource Sharing (CORS) is a relevant specification with the emergence of HTML5 and JS clients that consume data via REST APIs.

Often, the host that serves the JS (e.g. example.com) is different from the host that serves the data (e.g. api.example.com). In such a case, CORS enables cross-domain communication.

Spring provides first-class support for CORS, offering an easy and powerful way of configuring it in any Spring or Spring Boot web application.

Further reading:

Fixing 401s with CORS Preflights and Spring Security

Learn how to fix HTTP error status 401 for CORS preflight requests

Spring Webflux and CORS

A quick and practical guide to working with CORS and Spring Webflux.

2. Controller Method CORS Configuration

Enabling CORS is straightforward — just add the annotation @CrossOrigin.

We can implement this in several different ways.

2.1. @CrossOrigin on a @RequestMapping-Annotated Handler Method

@RestController
@RequestMapping("/account")
public class AccountController {

    @CrossOrigin
    @RequestMapping(method = RequestMethod.GET, path = "/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

In the example above, we only enabled CORS for the retrieve() method. We can see that we didn't set any configuration for the @CrossOrigin annotation, so it uses the defaults:

  • All origins are allowed.
  • The HTTP methods allowed are those specified in the @RequestMapping annotation (GET, for this example).
  • The time that the preflight response is cached (maxAge) is 30 minutes.

2.2. @CrossOrigin on the Controller

@CrossOrigin(origins = "http://example.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

    @RequestMapping(method = RequestMethod.GET, path = "/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

This time, we added @CrossOrigin on the class level. So, both retrieve() and remove() methods have it enabled. We can customize the configuration by specifying the value of one of the annotation attributes: origins, methods, allowedHeaders, exposedHeaders, allowCredentials, or maxAge.

2.3. @CrossOrigin on Controller and Handler Method

@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {

    @CrossOrigin("http://example.com")
    @RequestMapping(method = RequestMethod.GET, "/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

Spring will combine attributes from both annotations to create a merged CORS configuration.

Here, both methods will have a maxAge of 3,600 seconds, the method remove() will allow all origins, and the method retrieve() will only allow origins from http://example.com.

3. Global CORS Configuration

As an alternative to the fine-grained annotation-based configuration, Spring lets us define a global CORS configuration out of our controllers. This is similar to using a Filter-based solution but can be declared within Spring MVC and combined with a fine-grained @CrossOrigin configuration.

By default, all origins and GET, HEAD, and POST methods are allowed.

3.1. JavaConfig

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

The example above enables CORS requests from any origin to any endpoint in the application.

To lock this down a bit more, the registry.addMapping method returns a CorsRegistration object, which we can use for additional configuration. There’s also an allowedOrigins method that lets us specify an array of allowed origins. This can be useful if we need to load this array from an external source at runtime.

Additionally, there are also allowedMethods, allowedHeaders, exposedHeaders, maxAge and allowCredentials that we can use to set the response headers and customization options.

It is worth noting that since version 2.4.0, Spring Boot introduced allowedOriginPatterns in addition to just allowedOrigins. This new element gives more flexibility when defining patterns. Furthermore, when allowCredentials is true, allowedOrigins cannot contain the special value ‘*' since that cannot be set on the Access-Control-Allow-Origin response header. To solve this issue and allow the credentials to a set of origins, we can either list them explicitly or consider using allowedOriginPatterns instead.

3.2. XML Namespace

This minimal XML configuration enables CORS on a /** path pattern with the same default properties as the JavaConfig one:

<mvc:cors>
    <mvc:mapping path="/**" />
</mvc:cors>

It's also possible to declare several CORS mappings with customized properties:

<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>

4. CORS With Spring Security

If we use Spring Security in our project, we must take an extra step to make sure it plays well with CORS. That's because CORS needs to be processed first. Otherwise, Spring Security will reject the request before it reaches Spring MVC.

Luckily, Spring Security provides an out-of-the-box solution:

@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

This article explains it in more detail.

5. How It Works

CORS requests are automatically dispatched to the various registered HandlerMappings. They handle CORS preflight requests and intercept CORS simple and actual requests using a CorsProcessor implementation (DefaultCorsProcessor by default) to add the relevant CORS response headers (such as Access-Control-Allow-Origin).

CorsConfiguration allows us to specify how the CORS requests should be processed, including allowed origins, headers, and methods, among others. We can provide it in various ways:

  • AbstractHandlerMapping#setCorsConfiguration() allows us to specify a Map with several CorsConfigurations mapped onto path patterns such as /api/**.
  • Subclasses can provide their own CorsConfiguration by overriding the AbstractHandlerMapping#getCorsConfiguration(Object, HttpServletRequest) method.
  • Handlers can implement the CorsConfigurationSource interface (like ResourceHttpRequestHandler does now) to provide a CorsConfiguration for each request.

6. Conclusion

In this article, we showed how Spring provides support for enabling CORS in our application.

We started with the configuration of the controller. We saw that we only need to add the annotation @CrossOrigin to enable CORS to either one particular method or the entire controller.

Also, we learned that in order to control the CORS configuration outside of the controllers, we can perform this smoothly in the configuration files using either JavaConfig or XML.

The full source code for the examples is available over on GitHub.

Course – LS (cat=Spring)

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!