CORS with Spring

1. Overview

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

In many cases, 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 the 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

Read more

Spring Webflux and CORS

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

Read more

2. Controller Method CORS Configuration

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

We may implement this in a number of different ways.

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

[source,java,gutter:,true]

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

    @CrossOrigin
    @RequestMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

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

In the example above, CORS is only enabled for the retrieve() method. We can see that we didn’t set any configuration for the @CrossOrigin annotation, so the default configuration takes place:

  • All origins are allowed

  • The HTTP methods allowed are those specified in the @RequestMapping annotation (for this example is GET)

  • The time that the preflight response is cached (maxAge) is 30 minutes

2.2. @CrossOrigin on the Controller

[source,java,gutter:,true]

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

    @RequestMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

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

Since @CrossOrigin is added to the Controller 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

[source,java,gutter:,true]

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

    @CrossOrigin("http://example.com")
    @RequestMapping("/{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.

In this example both methods will have a maxAge of 3600 seconds, the method remove() will allow all origins but 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 some global CORS configuration out of your controllers. This is similar to using a Filter based solution but can be declared within Spring MVC and combined with fine-grained @CrossOrigin configuration.

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

3.1. JavaConfig

[source,java,gutter:,true]

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

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

Additionally, there’s also allowedMethods, allowedHeaders, exposedHeaders, maxAge, and allowCredentials which can be used to set the response headers and provide us with more customization options.

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 is 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. How It Works

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

CorsConfiguration allows one to specify how the CORS requests should be processed: allowed origins, headers and methods among others. This may be provided in various ways:

  • AbstractHandlerMapping#setCorsConfiguration() allows one to specify a Map with several CorsConfigurations mapped onto path patterns such as /api/**

  • Subclasses may provide their own CorsConfiguration by overriding the AbstractHandlerMapping#getCorsConfiguration(Object, HttpServletRequest) method

  • Handlers may implement the CorsConfigurationSource interface (like ResourceHttpRequestHandler now does) in order to provide a CorsConfiguration for each request

5. 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 in order to enable CORS either to one particular method or the entire controller.

Finally, we also saw that if we want to control the CORS configuration outside of the controllers we can perform this easily in the configuration files – either using JavaConfig or XML.

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

Leave a Reply

Your email address will not be published.