带Authorization头的Angular请求遭CORS拦截,Spring Boot配置无效求助
问题分析与解决方案
核心问题1:CORS配置中allowedOrigins格式错误
你的Spring Boot配置里allowedOrigins("http://localhost:4200/**")写法错误——Origin仅包含协议、域名和端口,不能带路径后缀。正确写法应为"http://localhost:4200"。
修改后的CORS配置:
@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/v1/**") .allowedOrigins("http://localhost:4200") // 移除末尾的/** .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 显式添加OPTIONS以处理预检请求 .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); }
核心问题2:Angular请求需配置withCredentials
后端开启allowCredentials(true)后,前端请求必须同步设置withCredentials为true,否则浏览器会拦截响应。在Angular的HTTP请求中添加该配置:
// 示例HttpClient请求代码 this.http.post('http://localhost:8080/api/v1/poll/public', {start: 0, length: 5}, { headers: new HttpHeaders({ 'Authorization': 'Bearer ' + yourToken }), withCredentials: true // 必须添加此行 } ).subscribe(...);
额外检查项
- 若使用Spring Security,需确保安全过滤器链未覆盖CORS配置,需显式关联CORS并允许OPTIONS请求:
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.cors(cors -> cors.configurationSource(corsConfigurationSource())) .authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) .csrf(csrf -> csrf.disable()); // 无需CSRF时关闭,避免干扰请求 return http.build(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "Accept")); configuration.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/api/v1/**", configuration); return source; }
- 若浏览器提示“Request header field authorization is not allowed”,可显式指定允许的请求头,替代通配符
*(部分浏览器对通配符支持有限):
.allowedHeaders("Authorization", "Content-Type", "Accept")
内容的提问来源于stack exchange,提问作者Ayah K Alrifai
相关产品推荐
相关产品推荐

