为什么我的 CORS 过滤器不起作用?春季启动

发布于 2025-01-11 13:54:49 字数 4005 浏览 0 评论 0原文

我的后端设置在 REST 控制器上的 CORS 方面存在很大问题。我尝试应用各种过滤器,但没有一个起作用。 这是我当前的 CORS 过滤器实现,

    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);
    
        }
    
    
    
    }

因为它不起作用,所以我还添加了 CORS 配置器,

    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");
                }
            };
        }
    }

它也不起作用。 我将 CORS 注释应用于每个控制器,

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

但仍然没有帮助。

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.

这个问题困扰了我好几个星期,我不知道该怎么办了。我非常感谢这里的好建议。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫卆 2025-01-18 13:54:49

我不明白为什么您要创建一个额外的过滤器,因为通常实现 WebMvcConfigurer 就足够了 - 至少根据我的知识和经验。

例如,您是否尝试过以下配置:

@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 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文