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

标签 spring spring-boot spring-mvc spring-security 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控制台的截图:

enter image description here

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

最佳答案

我已通过创建新的 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;
    }

}

关于Spring Boot CORS 过滤器 - CORS 预检 channel 未成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36809528/

相关文章:

spring - 试图让 Spring/Consul/Vault 一起工作

javascript - 如何在三元运算符上告诉 javascript "any number bigger than"?

angularjs - Spring Boot GUI 测试 Selenium WebDriver

java - 如何在 Spring 中将 bean 集合创建为 XML Java 配置?

java - 使用 BeanUtils.copyProperties 复制特定字段?

java - Session.close() 对 Spring openSessionInView 有影响吗?

mysql - Spring Framework JpaRepository 通过 findAll() 方法返回第一个表行的重复项

angular - 部署后从 URL 中删除 # 不起作用 - HTTP 404

java - 无法使用 Apache CXF Soap 通过代理建立隧道

java - 如何在Spring MVC中正确使用外部文件?