Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 680
C96 Avatar asked Sep 14 '20 12:09

C96


People also ask

How do I fix CORS header Access-Control allow Origin missing?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.

How do you fix CORS origin error?

Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.

How do I fix cross origin request blocked?

In order to fix CORS, you need to make sure that the API is sending proper headers (Access-Control-Allow-*). That's why it's not something you can fix in the UI, and that's why it only causes an issue in the browser and not via curl: because it's the browser that checks and eventually blocks the calls.


4 Answers

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("*");
    }
}
like image 189
Sathia Avatar answered Oct 24 '22 05:10

Sathia


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");
          }
       };
   }
}
like image 26
Ezequiel Falcon Avatar answered Oct 24 '22 07:10

Ezequiel Falcon


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/

like image 45
Antonio Vida Avatar answered Oct 24 '22 06:10

Antonio Vida


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; 
} 
like image 20
BarbetNL Avatar answered Oct 24 '22 05:10

BarbetNL