10

Hi I cant disable CORS in my project. I use a custom filter and Spring Security Config for the CORS configuration. I have seen this excellent answer: Can you completely disable CORS support in Spring?

but when I have tried the below implementation I still get the CORS error:

CORS configuration:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class CorsFilter @Autowired
constructor() : CorsFilter(configSrc()) {
    companion object {

    private fun configSrc(): UrlBasedCorsConfigurationSource {
        val config = CorsConfiguration()
        config.allowCredentials = true
        config.addAllowedOrigin("http://127.0.0.1:3000")
        config.addAllowedHeader("*")
        config.addAllowedMethod("*")
        val src = UrlBasedCorsConfigurationSource()
        src.registerCorsConfiguration("/**", config)
        return src
    }
}

}

Ive also tried setting the allowed origin to be like below with no results:

config.addAllowedOrigin("http://127.0.0.1:3000")

These are the Response headers from the proceeding OPTIONS request:

enter image description here

This is the exact error I am getting: enter image description here

Could you please point out any additional ideas or why this might be happening? I thought that this would be a simple to fix issue but it has ended up consuming quite a lot of my time.

Thank you

C96
  • 477
  • 8
  • 33
  • 1
    And are you sure that the `Access-Control-Allow-Origin` header is present on the response you get from the URL that you masked with green in your error message? (Is the image of the response headers of this masked URL?) – Ivar Sep 14 '20 at 12:31
  • How could I check that? Do I need access to the front end, which is where the request comes from? – C96 Sep 14 '20 at 12:36
  • 1
    Yes. I assume that the first image (with the response headers) is also from your browser. In the network tab in your browsers developer tools you should find this specific call (the one masked with green in your error message) and check if it contains this header. The error message seems to suggest it doesn't. That endpoint is the one that needs to return this response header. – Ivar Sep 14 '20 at 12:40
  • The Access-Control-Allow-Origin header is present as a response header with value "http://127.0.0.1:3000". The image of the response headers is of this masked URL – C96 Sep 14 '20 at 14:16
  • Are you using Google Chrome? If so, then this is most likely the cause: https://stackoverflow.com/questions/10883211/deadly-cors-when-http-localhost-is-the-origin – Ivar Sep 14 '20 at 14:23
  • Have you tried with `config.addAllowedOrigin("*")`? You may replace `*` with domain in the production and can create the configurations according to the profiles – Romil Patel Sep 17 '20 at 10:38
  • Yes. That is what I tried first. I also tried config.addAllowedOrigin("http://127.0.0.1:3000") which is the localhost where the app I run sends requests from – C96 Sep 17 '20 at 10:46
  • Do you have cors filter configured in your spring security config ? something like http.cors() ? – SKumar Sep 17 '20 at 11:17
  • I only have csrf().disable() on my securityConfig file – C96 Sep 17 '20 at 11:20
  • please check my answer here https://stackoverflow.com/a/63143499/11244881. With Spring Security, you need to additionally configure cors filter. – SKumar Sep 17 '20 at 11:32

6 Answers6

2

You can try adding CORS mapping in the application class in this way:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/v1/**")
                .allowedHeaders("*")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowCredentials(true)
                .maxAge(3600);
            }
        };
    }

https://spring.io/guides/gs/rest-service-cors/

Antonio Vida
  • 757
  • 4
  • 16
2

I had it working with this configuration

@Configuration
public class CorsConfig {
   @Bean
   public WebMvcConfigurer corsConfigurer() {
       return new WebMvcConfigurer() {
          @Override
          public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:4200");
          }
       };
   }
}
Ezequiel Falcon
  • 316
  • 2
  • 5
1

Assuming you work with SpringBoot security:

Add the following in your configuration class (which extends WebSecurityConfigurerAdapter and has @EnableWebSecurity annotation), add cors configuration:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            //other config
    }
//TODO needs to be secured on domain you wants to allow 
@Bean CorsConfigurationSource corsConfigurationSource() { 
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues()); 
return source; 
} 
BarbetNL
  • 408
  • 2
  • 16
1

This worked for me.

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    // We don't need CSRF for this example
    httpSecurity.csrf().disable().cors().configurationSource(corsConfigurationSource())
    ....
}



    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowCredentials(true);
        // the below three lines will add the relevant CORS response headers
        configuration.addAllowedOrigin("*");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
Raw
  • 461
  • 7
  • 15
1

Add the below class to resolve the CORS issue.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*").allowedMethods("*");
    }
}
Sathiamoorthy
  • 8,831
  • 9
  • 65
  • 77
1

To suggest an alternative, you could use something such as the package http-proxy-middleware (https://github.com/chimurai/http-proxy-middleware) on your front end, you can use this to change your origin URL and proxy the Origin header