FrancMo
FrancMo

Reputation: 2679

Spring Boot CORS issue

I am trying to learn spring with this tutorial:

https://spring.io/guides/tutorials/react-and-spring-data-rest/

but I am doing frontend app as a separate app. While making a call to: http://localhost:8080/api/employees

how to enable CORS globally ? thanks!

Tried in Application with:

@Bean
    public WebMvcConfigurer configurer()
    {
        return new WebMvcConfigurer()
        {
            @Override
            public void addCorsMappings(CorsRegistry registry)
            {
                registry.addMapping("/api/*").allowedOrigins("http://localhost:8000");
            }
        };
    }

but it does not help

did some testing with custom @RestController like here:

https://spring.io/guides/gs/rest-service-cors/#global-cors-configuration and calling http://localhost:8080/api/greeting from external frontend app works fine, only those rest endpoints CRUD auto generated via spring are not allowed CORS there.. How to avoid this issue ?

Upvotes: 0

Views: 3436

Answers (3)

Doktor
Doktor

Reputation: 91

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .maxAge(3600L)
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .allowCredentials(true);
    }
}

Upvotes: 0

FrancMo
FrancMo

Reputation: 2679

Adding:

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Note this is a very simple CORS filter that is wide open.
 * This would need to be locked down.
 * Source: https://stackoverflow.com/questions/39565438/no-access-control-allow-origin-error-with-spring-restful-hosted-in-pivotal-web
 */
@Component
public class CORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

helped

Upvotes: 0

riorio
riorio

Reputation: 6816

Try adding this to your main application class file:

    @Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

Upvotes: 1

Related Questions