Angular与Spring Boot本地运行遇CORS拦截、GET请求报net::ERR_FAILED问题
本地运行Angular+Spring Boot整合应用跨域报错问题
已完成的初步配置
- 后端禁用
csrf() - 后端对所有路径的
OPTIONS预检请求放行
运行时报错明细
- CORS策略拦截报错:从源地址
http://localhost:4200发起的XMLHttpRequest请求访问http://localhost:8080/hello/variable/paraan时,被CORS策略拦截,提示请求资源的响应中不存在Access-Control-Allow-Origin响应头。 - 浏览器控制台网络报错:
GET http://localhost:8080/hello/variable/user net::ERR_FAILED,报错定位在zone-evergreen.js:2845
端侧配置代码
Angular端 welcome-data.service.ts 业务代码
executeHelloWorldBeanServicePathVarible(name) { let basicAuthHeaderString=this.createBasicAuthenticationHttpHeader(); let headers=new HttpHeaders({ Authorization:basicAuthHeaderString }) return this.http.get<helloWorldBean>( `http://localhost:8080/hello/variable/${name}`, {headers} ); } createBasicAuthenticationHttpHeader(){ let username='user' let password='dummy' let basicAuthHeaderString='Basic' + window.btoa(username + ':' + password); return basicAuthHeaderString; }
Spring Boot端 初始版 SpringSecurityConfigurationBasicAuth.java 安全配置
package com.practice.rest.webservices.restfulwebservices.basic.auth; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.bind.annotation.CrossOrigin; @Configuration @EnableWebSecurity public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers(HttpMethod.OPTIONS,"/**").permitAll() .anyRequest().authenticated() .and() .httpBasic(); } }
调整后的 SpringSecurityConfigurationBasicAuth.java 安全配置(新增CorsFilter Bean)
package com.practice.rest.webservices.restfulwebservices.basic.auth; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration @EnableWebSecurity public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers(HttpMethod.OPTIONS,"/**").permitAll() .anyRequest().authenticated() .and() .httpBasic(); } @Bean public CorsFilter corsFilter() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin(CorsConfiguration.ALL); config.addAllowedHeader("*"); config.addExposedHeader("Authorization"); 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); } }
当前问题状态
完成上述配置调整后,跨域拦截及请求失败的报错仍未解决。
问题根因
- Spring Security过滤链优先级错误:自定义
CorsFilter未接入安全过滤链最前端,请求在进入CORS校验环节前就被认证逻辑拦截,返回的401响应未携带CORS相关头信息,最终触发浏览器CORS拦截提示。 - CORS配置与带凭证请求规则冲突:开启
allowCredentials(true)时,CORS规范不允许allowedOrigin使用*通配符,浏览器会直接拒绝这类响应。 - Angular端Basic认证头拼接错误:生成的认证头缺少
Basic与base64字符串之间的必要空格,后端无法识别认证信息,直接返回401响应,进一步放大跨域报错现象。
修复方案
后端调整
- 在Spring Security配置类的
configure方法中开启内置CORS支持,确保CORS校验优先于认证逻辑执行:@Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .cors() // 内置CORS支持,自动加载匹配的CORS配置源 .and() .authorizeRequests() .antMatchers(HttpMethod.OPTIONS,"/**").permitAll() .anyRequest().authenticated() .and() .httpBasic(); } - 修正CORS配置,将原通配符源替换为精确的前端源地址,替换原
CorsFilterBean为标准CORS配置源:@Bean public CorsConfigurationSource corsConfigurationSource() { final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); final CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("http://localhost:4200"); // 不能用*通配符 config.addAllowedHeader("*"); config.addExposedHeader("Authorization"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return source; }
Angular端调整
修正Basic认证头的拼接逻辑,补充必要的空格分隔:
let basicAuthHeaderString = `Basic ${window.btoa(username + ':' + password)}`;
内容的提问来源于stack exchange,提问作者Harry
相关产品推荐
相关产品推荐

