跨域配置问题:Allow Credentials

针对 withCredentials 导致的跨域问题处理

概要

浏览器端异常信息:

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.


思路

主要是因为前端默认启用了 credentials,有两种处理方式:

  1. 后端配置 addAllowedOriginPattern("*/") 和 setAllowCredentials(true)

    后端配置跨域时,推荐使用过滤器配置。因为继承 WebMvcConfigurer 实现跨域配置需要保持先后顺序,CORS配置在前,其他拦截器在后。而且,在另外的代码里重新实现 WebMvcConfigurer 后,会导致原 CORS 配置失效。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    
    @Configuration
    public class CorsConfiguration {
    
        /**
         * <p>Description:跨域过滤器</p>
         */
        @Bean
        public CorsFilter corsFilter() {
            //当前跨越请求最大有效时长,这里默认1小时
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            org.springframework.web.cors.CorsConfiguration corsConfiguration = new org.springframework.web.cors.CorsConfiguration();
            corsConfiguration.setAllowCredentials(false);
            //1.设置访问源地址,*表示所有IP
            corsConfiguration.addAllowedOriginPattern("*/");
            corsConfiguration.setAllowCredentials(true);
            //2.设置访问源请求头,*表示所有IP
            corsConfiguration.addAllowedHeader("*");
            //3.设置访问源请求方法,*表示所有IP
            corsConfiguration.addAllowedMethod("*");
            corsConfiguration.addExposedHeader("*");
            //4.对接口配置跨域设置
            source.registerCorsConfiguration("/**", corsConfiguration);
            return new CorsFilter(source);
        }
    }
    
  2. 前端配置 withCredentials: false

Licensed under CC BY-NC-SA 4.0
Comments
  • Latest
  • Oldest
  • Hottest
No comment yet.
Powered by Waline v2.15.8
Gear(夕照)的博客。记录开发、生活,以及一些不足为道的思考……