'Why my CORS filters don't work? Spring Boot

My backend setup has big issues with CORS on REST controllers. I tried to apply all sorts of filters, none of them work. This is my current CORS filter implementation

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.context.annotation.Bean;
    import org.springframework.stereotype.Component;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.CorsConfigurationSource;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.cors.reactive.CorsWebFilter;
    
    import org.springframework.web.filter.CorsFilter;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.Collections;
    
    @Slf4j
    @Component
    public class CORSFilter implements Filter {
        @Bean
        public CorsFilter corsFilter() {
            final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            final CorsConfiguration config = new CorsConfiguration();
            config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "authorization"));
            config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
            config.setAllowedOriginPatterns(Collections.singletonList("*"));
            config.setAllowCredentials(true);
            source.registerCorsConfiguration("/**", config);
            return new CorsFilter(source);
        }
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            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-Allow-Credentials", "true");
            servletRequest.getParameterMap();
            filterChain.doFilter(servletRequest, servletResponse);
    
        }
    
    
    
    }

Since it didn't work I also added CORS configurer

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class CORSconfigurer {
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurer() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/customer").allowedOrigins("http://localhost:3000");
                    registry.addMapping("/promotion").allowedOrigins("http://localhost:3000");
                }
            };
        }
    }

It also didn't work. I applied CORS adnotations to every controller

     @RestController
    @RequestMapping("/beacon")
    @RequiredArgsConstructor
    @CrossOrigin
    public class BeaconController {

Still it didn't help.

Error is this: Access to XMLHttpRequest at 'my-domain.dev/api-cms/customer/…' from origin 'localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This issue bothers me for weeks and I don't know what to do anymore. I would very much appreciate a good advice here.



Solution 1:[1]

I don't understand why you create an additional filter as usually implementing WebMvcConfigurer suffices - at least to my knowledge and experience.

Have you tried the following config for example:

@Configuration
public class WebConfig extends WebMvcAutoConfiguration implements WebMvcConfigurer {

    // Spring Boot 2.3.9.RELEASE
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(CorsConfiguration.ALL)
                .allowedMethods(CorsConfiguration.ALL)
                .allowedHeaders(CorsConfiguration.ALL)
                .exposedHeaders("Location")
                .allowCredentials(true);
    }
}

I know this config is not perfect as you permit every origin. However, it is a good starting point and worked for me in the past for quick prototypes.

Cheers

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