Search code examples
javaspringspring-securitycorscsrf

Unable to configure CSRF in Spring not to face CORS error


Following the Spring Boot's Issue #5834, in order to setup the proper CORS and lift the error supporting all the origins I have the following code:

@Configuration
@EnableWebSecurity
public class SecurityAdapter extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http)
        throws Exception
    {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry authorizeRequests = http.authorizeRequests();

        authorizeRequests.antMatchers("/logon_check").permitAll();
        authorizeRequests.antMatchers("/logon").permitAll();
        authorizeRequests.anyRequest().authenticated();

        http
            .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and()
            .cors()
        .and()
            .httpBasic()
        .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        // setAllowCredentials(true) is important, otherwise:
        // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
        configuration.setAllowCredentials(true);
        // setAllowedHeaders is important! Without it, OPTIONS preflight request
        // will fail with 403 Invalid CORS request
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

And

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
}

But the OPTIONS preflight request returns 403:

XMLHttpRequest cannot load http://192.168.2.10:8080/logon_check. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.2.10:4200' is therefore not allowed access. The response had HTTP status code 403.

These are the request headers:

OPTIONS /logon_check HTTP/1.1
Host: 192.168.2.10:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: GET
Origin: http://192.168.2.10:4200
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36
Access-Control-Request-Headers: x-requested-with
Accept: */*
Referer: http://192.168.2.10:4200/logon
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,fa;q=0.6

And response headers:

HTTP/1.1 403
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Length: 20
Date: Mon, 26 Jun 2017 23:56:06 GMT

Can someone help me configure the Spring right so all origins are passed through?


Solution

  • I found a way to fix the problem but I'm not sure if this way of fixing is the right way of doing it or not.

    After a couple of hours tracing Spring's code, I realized that the problem is with the HTTP headers that are allowed in the request. So changing the this line could resolve the problem:

    configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type", "X-Requested-With", "X-XSRF-TOKEN"));
    

    In the above line, I've added "X-Requested-With", "X-XSRF-TOKEN" to the list of the headers allowed by the request to have. These two extra headers are the ones I needed to add. There might be some other cases / browsers which some other headers might be needed. So a general fix could be:

    configuration.setAllowedHeaders(ImmutableList.of("*"));
    

    But again, I'm not sure if this could be security risk or not.