C96
C96

Reputation: 529

Issue with CORS and error and Access-Control-Allow-Origin header

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

Upvotes: 10

Views: 2202

Answers (6)

Andrew Glazier
Andrew Glazier

Reputation: 159

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

Upvotes: 1

Sathiamoorthy
Sathiamoorthy

Reputation: 11580

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("*");
    }
}

Upvotes: 1

Ezequiel Falcon
Ezequiel Falcon

Reputation: 336

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");
          }
       };
   }
}

Upvotes: 2

Antonio Vida
Antonio Vida

Reputation: 872

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/

Upvotes: 2

Raw
Raw

Reputation: 506

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

Upvotes: 1

BarbetNL
BarbetNL

Reputation: 507

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

Upvotes: 1

Related Questions