Chetan
Chetan

Reputation: 1151

CORS filter for spring boot not working

I have added the following under @Configuration

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    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);
    final FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

As well as :

@Bean
    public WebMvcConfigurer mvcConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "GET", "OPTIONS");
            }
        };
    }

I do not enable both of them ,

But when I fire the CORS preflight request using CURL I get the following :

 HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Access-Control-Allow-Origin: www.example.com
< Vary: Origin
< Access-Control-Allow-Credentials: true
< Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
< Content-Length: 0
< Date: Mon, 20 Jun 2016 08:26:06 GMT
<
* Connection #6 to host localhost left intact

Using :

curl -H "Origin: www.example.com" \ -H "x-auth-token: 93f8ddb4-d2db-4c8f-b30e-a9fb8468437b" -H "Access-Control-Request-Method: POST" \ -H "Access-Control-Request-Headers: X-Requested-With" \ -X OPTIONS --verbose \ http://localhost:8181

I feel the ideal output has to be something like :

http://learntogoogleit.com/post/61327173902/cors-preflight-request-testing-in-curl

I get the CORS preflight model not supported using angular client

Upvotes: 0

Views: 1544

Answers (1)

Dhanabalan
Dhanabalan

Reputation: 572

Can you try @CrossOrigin annotation top of your controller class?

Upvotes: 0

Related Questions