You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:05:00