The new Certification Class of Learn Spring Security is out:

>> CHECK OUT THE COURSE

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.

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 for configuring it.

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

@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

@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 

@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

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

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

Go deeper into Spring Security with the course:

>> LEARN SPRING SECURITY

Sort by:   newest | oldest | most voted
Ido
Guest

Excelent Article. But, it’s possible use a regular pattern in allowedOrigins? At my work I need to test a REST service in a develop enviroment and their host is variable at the creation moment, eg: http://www.devXXXXXX.company.com where XXXXXX is a random number.

Eugen Paraschiv
Guest

Hey Ido,
I’m glad you like the article.
No – regex is not supported in allowedOrigins. The * wildcard is the only other option here. Have a look at the CorsConfiguration – checkOrigin implementation to see exactly how the check is done.
Hope that helps. Cheers,
Eugen.

Don Han
Guest

Recently I found WebMvcConfigurerAdapter reset my jackson.serialization.write-dates-as-timestamps config. I’m using a WebMvcConfigurer bean instead.

Jagruti Frank
Guest

Hi
I am getting Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://servername:8090’ is therefore not allowed access. The response had HTTP status code 403.
thisis in my appconfig extending WebMvcConfigurerAdapter
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping(“/**”);
}

Any idea
Appreciate your help
Thanks

Grzegorz Piwowarek
Guest

@jagruti_frank:disqus the problem is happening with the code samples or with your own project?

Jagruti Frank
Guest
its in my own project, apologies I missed it I tried everything adding corsmappingusing WebMvcConfigurerAdapter , also in web.xml project stucture: Angular2 –>restAPI call (with spring security) registry.addMapping(“/**”) .allowedOrigins(“http://localhost:8080”, “http://servername:8090”) .allowedMethods(“POST”, “GET”, “PUT”, “OPTIONS”, “DELETE”) .allowedHeaders(“X-Auth-Token”, “Content-Type”) .exposedHeaders(“custom-header1”, “custom-header2”) .allowCredentials(false) .maxAge(4800); Appreciate your help on this.
Grzegorz Piwowarek
Guest

What happens when you make a call from http://localhost:8080? Are you sure your config is getting registered properly?

Jagruti Frank
Guest

Yes local host:8090 works

Grzegorz Piwowarek
Guest

Ok, in this case it will be super hard to answer the question without looking at the code. If you could open a PR to our codebase with code reproducing the issue, we would be glad to have a look

Jagruti Frank
Guest

will try to do tomorrow

Jagruti Frank
Guest

please provide me link and let me know how to open PR( what does this means?), Appreciate your help.

Grzegorz Piwowarek
Guest

https://github.com/eugenp/tutorials
This is our codebase where we store snippets.
Here you can find some more info about the PR procedure: https://yangsu.github.io/pull-request-tutorial/

Jagruti Frank
Guest

Thanks, I got the reason but dont know how to resolve, any lights will be helpful.
Login works (/auth/login)
but the restaPI call /channel change doesnt work
code snippet
// edited out

I dont want to permitall, but only who has role can do the channel change
Appreciate your help, how to resolve this.

Eugen Paraschiv
Guest

Hey @jagruti_frank:disqus – quick note – since there’s a lot of code to deal with here (I edited that out) – it’s better to follow up over email. That way we keep the comments here easier to read 🙂
Cheers,
Eugen.

Jagruti Frank
Guest

Thanks Eugen, would you please share the email?

Eugen Paraschiv
Guest

You can simply reply to any of my emails (I assume you’re subscribed to the list).
Hope that helps. Cheers,
Eugen.

wpDiscuz