'CORS settings in Spring boot does not work

I have Springboot (v 2.0) application. I enabled CORS in the application.properties as below.

management.endpoints.web.cors.allowed-origins=http://xxxx.yyyyy.me
management.endpoints.web.cors.allowed-methods=GET,POST
management.endpoints.web.cors.allowed-headers=Authorization,Cache-Control,Content-Type,Accept,X-Requested-With,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Origin
management.endpoints.web.cors.exposed-headers=Access-Control-Expose-Headers,Authorization,Cache-Control,Content-Type,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Origin

Also I had to remove the annotation @EnableWebMvc from the web config because I don't want to use Thymleaf templates (so I use my own add view controller like below.)

  @Override
  public void addViewControllers(ViewControllerRegistry registry)
  {
    registry.addViewController("/").setViewName("forward:/index.html");
    registry.addViewController("/myProfile").setViewName("forward:/index.html");
  }

also I added the CORS config bean in the main java class like below.

public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://xxxx.yyyyy.me")
        .allowedHeaders("Authorization","Cache-Control","Content-Type","Accept","X-Requested-With","Access-Control-Allow-Origin","Access-Control-Allow-Headers","Origin")
          .exposedHeaders("Access-Control-Expose-Headers","Authorization","Cache-Control","Content-Type","Access-Control-Allow-Origin","Access-Control-Allow-Headers","Origin");
      }
    };
  }

Also in the web security, I added following:

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
       http.cors();
    }

But still no luck. When I get request from http://xxxx.yyyyy.me, I get CORS error like below.

Access to XMLHttpRequest at 'https://abcde.com/api/traveller/findTravellers?fromDate=&toDate=&gender=&orderBy=&minAge=&maxAge=&keyword=&languages=&placeObj=&needAccommodation=false&haveAccommodation=false&needCar=false&haveCar=false&lookingFriends=false&withPhotoOnly=false&page=0&totalVisible=7&size=20&totalCount=0' from origin 'http://xxxx.yyyyy.me' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Any idea how to fix this? thanks a lot.



Solution 1:[1]

/**
 * CorsConfiguration Bean Configuration.
 * 
 * @return corsConfigurationSource.
 */
@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(ImmutableList.of("*"));
    configuration.setAllowedMethods(ImmutableList.of(HttpMethod.HEAD.name(), HttpMethod.OPTIONS.name(), HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.PUT.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
    // setAllowCredentials(true) is important, otherwise:
    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the
    // request's credentials mode is 'include'.
    configuration.setAllowCredentials(false);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(ImmutableList.of(HttpHeaders.AUTHORIZATION, HttpHeaders.CACHE_CONTROL, HttpHeaders.CONTENT_TYPE, HttpHeaders.ACCEPT, ORGA_ID));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

Solution 2:[2]

I have used like below which is working perfectly fine. Please see my configuration file.

WebConfig.java

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*");
    }
}

Solution 3:[3]

Try below implementation. It always works for me. Replace * against Access-Control-Allow-Origin with your specific origin.

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-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Authorization, Origin, Accept, Access-Control-Request-Method, Access-Control-Request-Headers");

        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

Solution 4:[4]

just try to add

public class CorsFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        chain.doFilter(req, res);

    }

Solution 5:[5]

I was having the same issue. What I had failed to understand is that management.endpoints.web.cors properties are simply for Spring Actuator management endpoints (e.g. /health).

To actually set the CORS properties for the regular service endpoints, one needs to programatically set them, as other answers here correctly show.

Solution 6:[6]

Variants for register your self CORS processor depends on type of controller registration:

  • default variant with @Controller used RequestMappingHandlerMapping for register CORS
  • you used function style registration

By my opinion, you may try extend AbstractUrlHandlerMapping or another from hierarchy. For finding concrete implementation you can stay in debug in function org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#registerHandler


Recently I self investigated looks like problem and used this method.
And my results:

  • extended class RequestMappingHandlerMapping
    • overrided method initCorsConfiguration for making behavior of configured paths
    • registered it by function io.github.iruzhnikov.webmvc.servlet.CorsPropWebMvcRegistrations#getRequestMappingHandlerMapping
    • registered it by function io.github.iruzhnikov.webmvc.servlet.CorsPropWebMvcConfigurationSupport#createRequestMappingHandlerMapping
  • extended classio.github.iruzhnikov.webmvc.servlet.SpringMvcCorsConfigurer
    • overrided method addCorsMappings for register new CorsConfig
    • registered id like of typical Bean

Solution 7:[7]

This is not a mice issue, but a problem with tab_model() and broom objects. See https://stackoverflow.com/a/70422199/17724015 and https://github.com/strengejacke/sjPlot/issues/385.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 codiallo
Solution 2 Community
Solution 3 Dhiraj Ray
Solution 4
Solution 5 Miguel
Solution 6
Solution 7 hanne