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

Angular 18携带Bearer Token请求在Spring Boot中获取空Header问题

问题排查与解决方案

针对你遇到的Angular请求携带Authorization头但Spring Boot无法获取的问题,以下是常见排查方向和解决方法:

1. 跨域(CORS)配置缺失

浏览器跨域请求时,预检请求(OPTIONS)需要服务器明确允许Authorization头,否则实际请求的该头会被浏览器过滤。

解决方法:

在Spring Boot中配置全局CORS规则,确保允许Authorization头:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:4200") // 替换为你的Angular项目域名
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("Authorization", "Content-Type") // 明确允许Authorization头
                .allowCredentials(true);
    }
}

如果使用Spring Security,需在安全链中启用CORS:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .cors(Customizer.withDefaults()) // 关联上述CORS配置
        .csrf(csrf -> csrf.disable()) // 前后端分离场景通常需关闭CSRF
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/auth/**").permitAll() // 放行登录等无需认证的接口
            .anyRequest().authenticated()
        );
    return http.build();
}

2. Angular代理配置问题

如果Angular使用代理转发请求,需确保代理配置正确传递请求头:

创建proxy.conf.json文件:

{
  "/users": {
    "target": "http://你的Spring Boot域名:端口",
    "secure": false,
    "changeOrigin": true,
    "preserveHostHeader": true
  }
}

在angular.json的serve配置中关联代理文件:

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "proxyConfig": "proxy.conf.json"
  }
}

3. 反向代理(如Nginx)丢失头

若Spring Boot部署在Nginx之后,需确保Nginx配置中传递Authorization头:

location / {
    proxy_pass http://localhost:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Authorization $http_authorization; # 关键配置,传递Authorization头
}

4. 浏览器缓存/插件干扰

  • 尝试使用浏览器隐私模式重新测试,排除缓存影响
  • 禁用广告拦截、隐私保护类插件,避免插件修改请求头

5. 拦截器执行顺序验证

虽然你的Angular拦截器代码看起来正确,但可额外验证:

  • 确认authService.getToken()能正确从localStorage取出有效Token
  • 在拦截器中打印authReq.headers.get('Authorization'),确认头已正确设置

内容的提问来源于stack exchange,提问作者msabate

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:10:20