Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot CORS filter - CORS preflight channel did not succeed

I need to add CORS filter to my Spring Boot web application.

I have added CORS mappings as described in the following documentation http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html

This is my config:

@Configuration @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter {      @Override     public void addCorsMappings(CorsRegistry registry) {         // @formatter:off            registry             .addMapping("/**")             .allowedOrigins(CrossOrigin.DEFAULT_ORIGINS)             .allowedHeaders(CrossOrigin.DEFAULT_ALLOWED_HEADERS)             .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")             .maxAge(3600L);         // @formatter:on     }  ...  } 

Right now when I'm trying to access my API I receiving a following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/api/v1.0/user. (Reason: CORS preflight channel did not succeed). 

This is a screenshot from FF console:

enter image description here

What am I doing wrong and how to properly configure CORS headers in order to avoid this issue ?

like image 802
alexanoid Avatar asked Apr 23 '16 10:04

alexanoid


People also ask

How do I enable CORS filter in spring boot?

Enable CORS in Controller Method We need to set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.

How do I fix invalid CORS request?

Go to https://www.getpostman.com/docs/capture in your chrome browser. Click on interceptor extension and then choose add to chrome. Once it is added there is a new icon top right of both the browser and postman that looks like a traffic light. In postman click this and it turns green.

What is CrossOrigin annotation?

This @CrossOrigin annotation enables cross-origin resource sharing only for this specific method. By default, its allows all origins, all headers, and the HTTP methods specified in the @RequestMapping annotation. Also, a maxAge of 30 minutes is used.


2 Answers

I have fixed this issue by creating a new CORS Filter:

@Component public class CorsFilter extends OncePerRequestFilter {      @Override     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {         response.setHeader("Access-Control-Allow-Origin", "*");         response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");         response.setHeader("Access-Control-Max-Age", "3600");         response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token");         response.addHeader("Access-Control-Expose-Headers", "xsrf-token");         if ("OPTIONS".equals(request.getMethod())) {             response.setStatus(HttpServletResponse.SC_OK);         } else {              filterChain.doFilter(request, response);         }     } } 

and added it to securty configuration:

.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class) 

UPDATED - More modern way nowadays which I switched to:

@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {      @Override     protected void configure(HttpSecurity http) throws Exception {          http             .cors()         .and()          ...     }      @Bean     public CorsConfigurationSource corsConfigurationSource() {         CorsConfiguration configuration = new CorsConfiguration();         configuration.setAllowedOrigins(Arrays.asList("*"));         configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));         configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));         configuration.setExposedHeaders(Arrays.asList("x-auth-token"));         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();         source.registerCorsConfiguration("/**", configuration);         return source;     }  } 
like image 102
alexanoid Avatar answered Sep 19 '22 13:09

alexanoid


Had the same issue getting CORS to work with spring data rest, this was the filter code I used.

    /**  * Until url{https://jira.spring.io/browse/DATAREST-573} is fixed  *   * @return  */ @Bean public CorsFilter corsFilter() {      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();     CorsConfiguration config = new CorsConfiguration();     //config.setAllowCredentials(true); // you USUALLY want this     config.addAllowedOrigin("*");     config.addAllowedHeader("*");     config.addAllowedMethod("OPTIONS");     config.addAllowedMethod("HEAD");     config.addAllowedMethod("GET");     config.addAllowedMethod("PUT");     config.addAllowedMethod("POST");     config.addAllowedMethod("DELETE");     config.addAllowedMethod("PATCH");     source.registerCorsConfiguration("/**", config);     return new CorsFilter(source); } 
like image 34
Romell Avatar answered Sep 18 '22 13:09

Romell