10

I'm trying to configure CORS in a Spring boot application that already has Basic auth set up.

I've searched in many places, including this answer, that points to Filter based CORS support in the official docs.

So far no luck.

My AJAX request is done this way. It works if done from same origin http://localhost:8080.

fetch('http://localhost:8080/api/lists', {
  headers: {
    'Authorization': 'Basic dXNlckB0ZXN0LmNvbToxMjM0NQ=='
  }
}

The AJAX request is done from a React app at http://localhost:3000, so I tried the following Spring boot CORS config:

@Configuration
class MyConfiguration {

    @Bean
    public FilterRegistrationBean corsFilter()
    {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        // Maybe I can just say "*" for methods and headers
        // I just copied these lists from another Dropwizard project
        config.setAllowedMethods(Arrays.asList("GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD"));
        config.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept",
            "Authorization", "Access-Control-Allow-Credentials", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods",
            "Access-Control-Allow-Origin", "Access-Control-Expose-Headers", "Access-Control-Max-Age",
            "Access-Control-Request-Headers", "Access-Control-Request-Method", "Age", "Allow", "Alternates",
            "Content-Range", "Content-Disposition", "Content-Description"));
        config.setAllowCredentials(true);

        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

My WebSecurityConfig:

@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.httpBasic().and()
            .authorizeRequests()
            .antMatchers("/", "/index.html").permitAll()
            .anyRequest().fullyAuthenticated();
    }
}

The fetch call from http://localhost:3000 displays this 401 error in the console:

Fetch API cannot load http://localhost:8080/api/lists. Response for preflight has invalid HTTP status code 401.

enter image description here

An in the network tab of chrome dev tools I see this OPTIONS request:

enter image description here

Community
  • 1
  • 1
Ferran Maylinch
  • 10,919
  • 16
  • 85
  • 100

3 Answers3

11

I think you need to allow OPTION requests into your web security config. Something like:

.antMatchers(HttpMethod.OPTIONS, "/your-url").permitAll()

Ignasi
  • 5,887
  • 7
  • 45
  • 81
  • Thanks! You were right! For now, just to see it works, I used `.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()`. It works with my `FilterRegistrationBean`. Maybe it also works with the `CorsFilter`, but the problem was the OPTIONS call was being blocked. – Ferran Maylinch Dec 15 '16 at 13:16
5

The browser checks CORS settings via a request with OPTIONS header. And if you've configured authorization, OPTIONS request will be blocked as unauthorized.

You can simply allow OPTIONS request via cors support in WebConfigurerAdapter.

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ...
        http.cors();
    }
}

Check this link for more info: https://www.baeldung.com/spring-security-cors-preflight

3

Try this:

@Configuration
public class CorsConfig {

  @Bean
  public CorsFilter corsFilter() {

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(false); //updated to false
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("POST");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
  }

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

}
Mike3355
  • 11,305
  • 24
  • 96
  • 184
  • Thank you but same result... I've also added my config setting to your solution but nothing changes. I'm not using Spring MVC, but I included your `WebMvcConfigurer` too just in case. – Ferran Maylinch Dec 10 '16 at 14:35
  • Are you using Boot with Angular 2 – Mike3355 Dec 10 '16 at 21:16
  • Why do you ask? I'm using React right now, to try it, but I'm planning to try Angular 2 too. Anyway, I'm calling the `@RestController` using the `fetch` function. I mean that no React components are involved in the call. – Ferran Maylinch Dec 11 '16 at 01:18