CORS preflight request fails due to a standard header

前端 未结 7 1087
灰色年华
灰色年华 2020-12-23 17:04

While debugging a CORS issue I am experiencing I\'ve found the following behaviour. Chrome makes the following OPTIONS preflight request (rewritten in CURL by Chrome itself)

相关标签:
7条回答
  • 2020-12-23 17:41

    i also faced the same issue and find solution for enabling global cors issue in spring boot

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

    after this , we need to enable CORS in spring security level also, so for this add cors() in your SecurityConfiguration class which extent WebSecurityConfigurerAdapter

     @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
    
            httpSecurity
                    .cors()
                    .and()
                    .csrf().disable()
                    .authorizeRequests()..
    
        }
    
    0 讨论(0)
  • 2020-12-23 17:42

    I came across this really while testing the CORS on our endpoints using test-cors.org website and it exhibits the exact same behavior that is described above.

    The approach that I did was to use the Global CORS filter instead of using the @CrossOrigin annotation.

    @Configuration
    class CorsConfig : WebMvcConfigurer {
        override fun addCorsMappings(registry: CorsRegistry) {
            registry.addMapping("/**")
                    .allowCredentials(true)
                    .allowedHeaders("*")
                    .allowedMethods("*")
                    .allowedOrigins("*")
                    .maxAge(3600)
        }
    }
    

    Note that you should not use @EnableWebMvc unless you want to take control Spring Boot Auto-configuration as noted here...which will probably cause some "issues" as noted here and here

    This next custom configuration is also needed (solution partially lifted from here) or else you will get that particular CORS pre-flight issue:

    @Configuration
    class CustomWebSecurityConfigurerAdapter : WebSecurityConfigurerAdapter() {
        override fun configure(http: HttpSecurity) {
            http.cors().and().csrf().disable()
        }
    }
    
    0 讨论(0)
  • 2020-12-23 17:51

    I added this as an answer because I couldn't format it well for the top voted answer.

    I found this post helpful as well: How to handle HTTP OPTIONS with Spring MVC?

    DispatchServlet must be configured to pass along options request, or else it never reaches the mapped request:

    ...
      <servlet>
        <servlet-name>yourServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
          <param-name>dispatchOptionsRequest</param-name>
          <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
    ...
    
    0 讨论(0)
  • 2020-12-23 17:55

    For me I have added @crossorigin annotation in each of controller api call.

    @CrossOrigin
    @PostMapping(path = "/getListOfIndividuals", produces = { "application/json" }, consumes = { "application/json" })
    public ResponseEntity<String> test(@RequestBody String viewIndividualModel)
            throws Exception {
        String individualDetails = globalService.getIndividualDetails(viewIndividualModel);
    
    
        finalString = discSpecAssmentService.getViewFormForDisciplineEvaluation( viewIndividualModel);
    
        return new ResponseEntity<String>(finalString, HttpStatus.OK);
    }
    
    0 讨论(0)
  • 2020-12-23 17:56

    After a lot of struggling, I finally found the problem. I configured a request mapping in Spring to handle OPTIONS traffic, like this:

    @RequestMapping(value= "/api/**", method=RequestMethod.OPTIONS)
    public void corsHeaders(HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with");
        response.addHeader("Access-Control-Max-Age", "3600");
    }
    

    I did not know that by default Spring uses a default CORS processor, and it seems it was interfering with my request mapping. Deleting my request mapping and adding the @CrossOrigin annotation to the appropriate request mappings solved the problem.

    0 讨论(0)
  • 2020-12-23 18:00

    I had the same issue. I've resolve it by adding 'OPTIONS' to allowed CORS methods in my Spring MVC configuration.

    @Configuration
    @EnableWebMvc
    @ComponentScan
    public class RestApiServletConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            super.addCorsMappings(registry);
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:3000", "http://localhost:8080")
                    .allowedMethods("GET", "PUT", "POST", "DELETE", "OPTIONS");
        }
    }
    
    0 讨论(0)
提交回复
热议问题