Spring Boot Cors“Access-Control-Max-Age”标头被浏览器忽略

Posted

技术标签:

【中文标题】Spring Boot Cors“Access-Control-Max-Age”标头被浏览器忽略【英文标题】:Spring Boot Cors "Access-Control-Max-Age" header is ignored by browsers 【发布时间】:2020-04-04 17:36:14 【问题描述】:

我对这个标题的期望是;浏览器在每个资源的最长期限内只发送一个options pre-flight request

但是,我尝试过的每个浏览器都会为每个请求发送options pre-flight request,即使是之前发送的请求也是如此。

我尝试禁用no-cache header,但没有任何改变。我分享了我的cors config 代码下面。顺便说一句,我的 spring boot 没有为 https/ssl 配置,但是域和前端反应应用 ,这可能是问题吗?

   @Bean
    public WebMvcConfigurer corsConfigurer()
        return new WebMvcConfigurer()  
            @Override
            public void addCorsMappings(CorsRegistry registry) 
                registry.addMapping("/**")
                        .allowedHeaders("*")
                        .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
                        .allowCredentials(true)
                        .allowedOrigins(ALLOWED_ORIGINS)
                        .exposedHeaders(AuthorizationController.AUTHENTICATION_KEY_NAME,
                                        RequestInterceptor.FAILURE_REASON_HEADER_KEY_NAME,
                                        RequestInterceptor.CONTENT_DISPOSITION_HEADER_KEY_NAME)
                        .maxAge(36000);
            
        ;
    
@Bean
        public CorsConfigurationSource corsConfigurationSource() 
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Collections.singletonList(ALLOWED_ORIGINS));
            configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
            configuration.setAllowedHeaders(Collections.singletonList("*"));
            configuration.setExposedHeaders(Arrays.asList(AuthorizationController.AUTHENTICATION_HEADER_NAME,
                                                        RequestInterceptor.ERROR_DESCRIPTION_HEADER_KEY_NAME,
                                                        RequestInterceptor.CONTENT_DISPOSITION_HEADER_KEY_NAME));
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        

我还在OncePerRequestFilter 中的每个请求中添加以下标头。

httpServletResponse.setHeader("Access-Control-Max-Age","36000");
httpServletResponse.setHeader("Access-Control-Allow-Origin",ALLOWED_ORIGINS);
httpServletResponse.setHeader("Access-Control-Allow-Headers","*");
httpServletResponse.setHeader("Access-Control-Allow-Methods","GET, PUT, POST, DELETE, HEAD, OPTIONS");
httpServletResponse.setHeader("Cache-Control","no-cache, no-store, max-age=36000")

【问题讨论】:

【参考方案1】:

您需要将要访问后端的域/主机列入白名单/

【讨论】:

以上是关于Spring Boot Cors“Access-Control-Max-Age”标头被浏览器忽略的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot 和 CORS

Spring Boot 和 CORS

Spring Boot 和 CORS

Spring Boot 和 CORS

Spring Boot 和 CORS

Spring Boot CORS支持