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 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 may 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 (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(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. Consequently, 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.

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 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 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 utilize to set the response headers and 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'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 the Spring Security in our project, we must take an extra step to make sure it plays well with CORS. It's because CORS must 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 extends WebSecurityConfigurerAdapter {
	    @Override
	    protected void configure(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: allowed origins, headers, and methods, among others. We may provide it 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) 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 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 smoothly in the configuration files – either using JavaConfig or XML.

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

Spring bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
16 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ido
Ido
3 years ago

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
3 years ago
Reply to  Ido

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
Don Han
3 years ago

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

Jagruti Frank
Jagruti Frank
3 years ago

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
Grzegorz Piwowarek
3 years ago
Reply to  Jagruti Frank

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

Jagruti Frank
Jagruti Frank
3 years ago

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
Grzegorz Piwowarek
3 years ago
Reply to  Jagruti Frank

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

Jagruti Frank
Jagruti Frank
3 years ago

Yes local host:8090 works

Grzegorz Piwowarek
Grzegorz Piwowarek
3 years ago
Reply to  Jagruti Frank

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
Jagruti Frank
3 years ago

will try to do tomorrow

Jagruti Frank
Jagruti Frank
3 years ago
Reply to  Jagruti Frank

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

Grzegorz Piwowarek
Grzegorz Piwowarek
3 years ago
Reply to  Jagruti Frank

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
Jagruti Frank
3 years ago

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
3 years ago
Reply to  Jagruti Frank

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
Jagruti Frank
3 years ago

Thanks Eugen, would you please share the email?

Eugen Paraschiv
3 years ago
Reply to  Jagruti Frank

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

Comments are closed on this article!