Spring Boot CORS 过滤器 - CORS 预检通道未成功

新手上路,请多包涵

我需要将 CORS 过滤器添加到我的 Spring Boot Web 应用程序中。

我添加了如下文档中所述的 CORS 映射 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html

这是我的配置:

 @Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // @formatter:off
        registry
            .addMapping("/**")
            .allowedOrigins(CrossOrigin.DEFAULT_ORIGINS)
            .allowedHeaders(CrossOrigin.DEFAULT_ALLOWED_HEADERS)
            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
            .maxAge(3600L);
        // @formatter:on
    }

...

}

现在,当我尝试访问我的 API 时,我收到以下错误:

 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/api/v1.0/user. (Reason: CORS preflight channel did not succeed).

这是FF控制台的截图:

在此处输入图像描述

我在做什么错以及如何正确配置 CORS 标头以避免此问题?

原文由 alexanoid 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 749
2 个回答

我通过创建一个新的 CORS 过滤器解决了这个问题:

 @Component
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, xsrf-token");
        response.addHeader("Access-Control-Expose-Headers", "xsrf-token");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}

并将其添加到安全配置中:

 .addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class)

更新 - 现在我切换到更现代的方式:

 @Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .cors()
        .and()

        ...
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
        configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

原文由 alexanoid 发布,翻译遵循 CC BY-SA 3.0 许可协议

正确处理飞行前 OPTIONS 请求是必要的,但不足以使跨站点资源请求正常工作。

在 OPTIONS 请求返回令人满意的标头后,对同一 URL 的任何后续请求的所有响应也必须具有必要的“Access-Control-Allow-Origin”标头,否则浏览器会吞下它们,甚至不会显示在调试器窗口中。 https://stackoverflow.com/a/11951532/5649869

原文由 Алексей Романов 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题