Spring Security下React调用Spring Boot出现CORS错误及后端异常
解决Spring Boot + React跨域CORS错误及后端IllegalArgumentException异常
问题说明
后端基于Spring Boot,前端采用React,前端访问后端时触发CORS错误,同时后端抛出以下异常:
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. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead
相关代码
Spring Security配置
@Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("OPTIONS"); config.addAllowedMethod("HEAD"); config.addAllowedMethod("GET"); config.addAllowedMethod("PUT"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); config.addAllowedMethod("PATCH"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } /** * This method is permitting endpoints * @author *** * */ @Override public void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity .cors() .and() .csrf().disable() .exceptionHandling().authenticationEntryPoint(handler).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() .antMatchers("/auth/**", "/swagger-ui.html", "/swagger-ui/index.html", "/swagger-ui/**", "/v3/api-docs/**") .permitAll() .anyRequest().authenticated(); httpSecurity.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); }
JWT过滤器代码
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String jwt = extractJwtFromRequest(request); if (jwt != null && jwtTokenProvider.validateJwtToken(jwt)) { String username = jwtTokenProvider.getUserIdFromJwtToken(jwt); UserDetails userDetails = userDetailsServiceImp.loadUserByUsername(username); if (userDetails != null) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities() ); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } } } catch (Exception e) { e.printStackTrace(); } filterChain.doFilter(request, response); }
错误截图
前端请求网络信息

浏览器CORS错误提示

解决方案
问题核心在于:当allowCredentials设为true时,allowedOrigins不能使用通配符*——浏览器要求带凭证的跨域请求必须明确指定允许的源,不能用*模糊匹配。提供两种解决方式:
明确指定允许的源
将config.addAllowedOrigin("*")替换为前端实际运行的域名,比如本地开发环境的http://localhost:3000:config.addAllowedOrigin("http://localhost:3000"); // 多环境可多次调用添加 // config.addAllowedOrigin("https://your-prod-domain.com");使用
allowedOriginPatterns替代allowedOrigins
若需要匹配多个源(如本地、测试环境),可使用支持通配符的allowedOriginPatterns:// 替换原config.addAllowedOrigin("*") config.addAllowedOriginPattern("*");
修改后重启后端服务即可生效。
内容的提问来源于stack exchange,提问作者Bertug
相关产品推荐
相关产品推荐

