Spring Security CORS Filter

In this article, we will look at the Spring Security CORS Filter and how we can configure this filter in our application.

Spring Security CORS Filter

Before we get into more details of Spring Security CORS filter, it’s really important that we understand what is CORS and what it brings to the Spring Security landscape which needs some special handling?

Because of security reason, browsers normally prohibits AJAX call to resources outside of the current origin. Let’s understand it what this means:

  1. Let’s say you have your bank account open in one tab on the browser.
  2. Browser will not allow site on the other tab to access the bank account site even though you have the correct credentials while calling it.

Cross-Origin resource sharing (CORS) is a specification from W3C implemented by most browsers. This mechanisms let us specify what cross domain requests are requests are allowed. This specification provides a more secure and robust process to access resources from cross origin than the less secure options like IFRAME or JSONP.

For security reasons, browsers restrict cross-origin HTTP requests started from scripts. For example, XMLHttpRequest follow the same-origin policy, which means a web application can only request resources from the same origin the application was loaded.

1. CORS

Now we have a basic understanding of the CORS. Let’s see how Spring Security CORS filter works. With Spring Security, it’s important that CORS must be processed before Spring Security because these pre-flight requests will no contains any cookies (e.g. JSESSIONID etc.) which are important components for Spring security.

Keep in mind that without these cookies, Spring security will determine that a user is not authenticated hence it’s important that CORS be processed before Spring security. Spring Security CORS filter will ensure that it’s handled first.

Spring Security CORS Filter
CORS

2. CORS Filter.

Spring security CORS filter will ensure that CORS are handled first. We can integrate CorsWebFilter with the help of CorsConfigurationSource. Let’s see how to add it to our application:

@Bean
CorsConfigurationSource corsConfigurationSource() {
	CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowedOrigins(Arrays.asList("https://javadevjournal.com"));
	configuration.setAllowedMethods(Arrays.asList("GET","POST"));
	UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
	source.registerCorsConfiguration("/**", configuration);
	

In case you want to add it under a common security configuration:

@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(request-> {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("https://javadevjournal.com"));
            configuration.setAllowedMethods(Arrays.asList("GET","POST"));
            configuration.setAllowedHeaders(List.of("*"));
            return configuration;
        }).and()
        ....
    }
}

2.1. Disable Spring Security CORS Filter

In case we want to disable the CORS Filter, we can easily do this in Spring security using the security config class:

@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

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

3. CORS Registry

Sometimes, you might still get the get a 401 No 'Access-Control-Allow-Origin' header is present on the requested resource error from the server. To handle this, we can also use the CorsRegistry.

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://localhost:7777");
        }
    };
}

Summary

In this article, we explored at the Spring Security CORS Filter. We understood what is CORS and how to handle it with Spring Security. We also checked what are the different options to configure CORS filter with Spring security. As always, you can check the source code at our GitHub repository.