0

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 ?

1
  • didn't get your question / problem? 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 ? Commented Jan 5, 2021 at 16:28

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

"java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*"since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead. "
This answer was correct until the last version of spring boot. From now on you can't use allow credentials set to true and allowrd origin with wildcard. Please look at stackoverflow.com/questions/66060750/…
addAllowedOriginPattern("*") worked for me.
0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.