CORS with spring-boot and angularjs not working CORS with spring-boot and angularjs not working angularjs angularjs

CORS with spring-boot and angularjs not working


import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;@Componentpublic class SimpleCORSFilter implements Filter {private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);public SimpleCORSFilter() {    log.info("SimpleCORSFilter init");}@Overridepublic void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {    HttpServletRequest request = (HttpServletRequest) req;    HttpServletResponse response = (HttpServletResponse) res;    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));    response.setHeader("Access-Control-Allow-Credentials", "true");    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");    response.setHeader("Access-Control-Max-Age", "3600");    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");    chain.doFilter(req, res);}@Overridepublic void init(FilterConfig filterConfig) {}@Overridepublic void destroy() {}}

No need extra define this filter just add this class. Spring will be scan and add it for you. SimpleCORSFilter.Here is the example: spring-enable-cors


I had been into the similar situation. After doing research and testing, here is my findings:

  1. With Spring Boot, the recommended way to enable global CORS is to declare within Spring MVC and combined with fine-grained @CrossOrigin configuration as:

    @Configurationpublic class CorsConfig {    @Bean    public WebMvcConfigurer corsConfigurer() {        return new WebMvcConfigurerAdapter() {            @Override            public void addCorsMappings(CorsRegistry registry) {                registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")                        .allowedHeaders("*");            }        };    }}
  2. Now, since you are using Spring Security, you have to enable CORS at Spring Security level as well to allow it to leverage the configuration defined at Spring MVC level as:

    @EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {    @Override    protected void configure(HttpSecurity http) throws Exception {        http.cors().and()...    }}

    Here is very excellent tutorial explaining CORS support in Spring MVC framework.


If you want to enable CORS without using filters or without config file just add

@CrossOrigin

to the top of your controller and it work.