Spring CORS - Spring @CrossOrigin example

Introduction to Spring @CrossOrigin annotation

Posted by Mr.Humorous 🥘 on June 2, 2019

CORS (Cross-origin resource sharing) allows a webpage to request additional resources into browser from other domains e.g. fonts, CSS or static images from CDNs. CORS helps in serving web content from multiple domains into browsers who usually have the same-origin security policy.

In this example, we will learn to enable Spring CORS support in Spring MVC application at method level and global level.

1. Spring CORS – Method level with @CrossOrigin

Spring MVC provides @CrossOrigin annotation. This annotation marks the annotated method or type as permitting cross origin requests.

1.1. Spring CORS allow all

By default, @CrossOrigin allows all origins, all headers, the HTTP methods specified in the @RequestMapping annotation and a maxAge of 30 minutes.

You can override default CORS settings by giving value to annotation attributes :

ATTRIBUTE DESCRIPTION
origins List of allowed origins. It’s value is placed in the Access-Control-Allow-Origin header of both the pre-flight response and the actual response.
  • * – means that all origins are allowed.
  • If undefined, all origins are allowed.
allowedHeaders List of request headers that can be used during the actual request. Value is used in preflight’s response header Access-Control-Allow-Headers.
  • * – means that all headers requested by the client are allowed.
  • If undefined, all requested headers are allowed.
methods List of supported HTTP request methods. If undefined, methods defined by RequestMapping annotation are used.
  • * – means that all headers requested by the client are allowed.
  • If undefined, all requested headers are allowed.
exposedHeaders List of response headers that the browser will allow the client to access. Value is set in actual response header Access-Control-Expose-Headers.
  • If undefined, an empty exposed header list is used.
allowCredentials It determine whether browser should include any cookies associated with the request.
  • false – cookies should not included.
  • "" (empty string) – means _undefined_.
  • true – pre-flight response will include the header Access-Control-Allow-Credentials with value set to true.
  • If undefined, credentials are allowed.
maxAge maximum age (in seconds) of the cache duration for pre-flight responses. Value is set in header Access-Control-Max-Age.
  • If undefined, max age is set to 1800 seconds (30 minutes).

1.2. @CrossOrigin at Class/Controller Level

@CrossOrigin(origins = "*", allowedHeaders = "*")
@Controller
public class HomeController
{
    @GetMapping(path="/")
    public String homeInit(Model model) {
        return "home";
    }
}

Read More – Spring 5 MVC Example

1.3. @CrossOrigin at Method Level

@Controller
public class HomeController
{
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    @GetMapping(path="/")
    public String homeInit(Model model) {
        return "home";
    }
}

1.4. @CrossOrigin Overridden at Method Level

homeInit() method will be accessible only from domain http://example.com. Rest other methods in HomeController will be accessible from all domains.

@Controller
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class HomeController
{
    @CrossOrigin(origins = "http://example.com")
    @GetMapping(path="/")
    public String homeInit(Model model) {
        return "home";
    }
}

2. Spring CORS – Global CORS configuration

2.1. Spring MVC CORS with WebMvcConfigurerAdapter

To enable CORS for the whole application, use WebMvcConfigurerAdapter to add CorsRegistry.

@Configuration
@EnableWebMvc
public class CorsConfiguration extends WebMvcConfigurerAdapter
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST");
    }
}

2.2. Spring Boot CORS with WebMvcConfigurer

In spring boot application, it is recommended to just declare a WebMvcConfigurer bean.

@Configuration
public class CorsConfiguration
{
    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

2.3. CORS with Spring Security

To enable CORS support through Spring security, configure CorsConfigurationSource bean and use HttpSecurity.cors() configuration.

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            //other config
    }

    @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;
    }
}