跨域:java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain

懒驴 2021年11月25日 404次浏览

错误:java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header.

遇到一个这样的错误问题,显然这个是跨域的问题。

首先我一开始实现了WebMvcConfigurer ,做了拦截器

@Configuration
public class HttpWebAppConfigurer implements WebMvcConfigurer {}

解决以上错误:
重写addCorsMappings方法

/***
     * 重写方法解决跨域问题
     * @param registry
     */
@Override
public void addCorsMappings(CorsRegistry registry) {
	registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600).allowedHeaders("*");
}

但是,这样的操作在我的环境spring-web-5.3.6并不好使,还是报同样的错误
最后研究了发现,原来是版本高的原因,之前的会报错的代码:

@Bean
public CorsFilter corsFilter() {
	final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
}

修改之后的代码

@Bean
public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许访问的客户端域名
        List<String> allowedOriginPatterns = new ArrayList<>();
        allowedOriginPatterns.add("*");
        corsConfiguration.setAllowedOriginPatterns(allowedOriginPatterns);
        corsConfiguration.setAllowCredentials(true);
        //corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

至此,问题得以解决。