Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling CORS globally in Spring Boot

I tried to enable CORS globally like this:

@Configuration
@ComponentScan("com.example")
@EnableWebMvc
public class OriginFilter extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

I also tried this approach:

@Configuration
public class OriginFilter implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
                .allowCredentials(true);
    }
}

But none of these worked for me.

An annotation @CrossOrigin for an individual class works, but I wanted to enable CORS it globally.

like image 599
Moler Avatar asked Aug 07 '18 06:08

Moler


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 can CORS configuration be enabled for the controller method?

27.2 Controller method CORS configuration You can add an @CrossOrigin annotation to your @RequestMapping annotated handler method in order to enable CORS on it.

How do I enable CORS in REST API?

Enable CORS support on a REST API resourceSign in to the API Gateway console at https://console.aws.amazon.com/apigateway . Choose the API from the APIs list. Choose a resource under Resources. This will enable CORS for all the methods on the resource.


2 Answers

I solved this problem by adding filterClass

@Component
public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept");
        response.setHeader("Access-Control-Expose-Headers", "Location");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
like image 40
Moler Avatar answered Sep 22 '22 16:09

Moler


You could indeed define your own Filter as you mentioned in your answer. Spring already has such a CorsFilter already though, so you don't have to create one yourself. Just register it as a bean and it should work:

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    // Don't do this in production, use a proper list  of allowed origins
    config.setAllowedOrigins(Collections.singletonList("*"));
    config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}
like image 161
g00glen00b Avatar answered Sep 18 '22 16:09

g00glen00b