Angular请求Spring登录接口成功但无法获取Authorization响应头
问题根因
这是浏览器CORS(跨域资源共享)规则限制导致的:
- Postman不属于浏览器环境,不受CORS规范约束,可直接读取所有响应头
- Angular应用运行在浏览器中,跨域请求(Angular默认运行在
localhost:4200、Spring运行在localhost:8080属于不同源)时,浏览器默认仅向JS暴露少量基础响应头,自定义的Authorization头不在默认暴露列表中,因此前端读取结果为null - 你的Spring安全配置中主动禁用了CORS(
http.cors().disable()),既没有配置合法的跨域规则,也未显式声明允许前端读取Authorization头
解决方案
仅需修改Spring后端配置,前端代码本身无需调整(已正确配置observe: 'response'获取完整响应对象)。
步骤1:移除CORS禁用配置
删除SecurityConfig中的http.cors().disable();代码行。
步骤2:配置跨域规则并显式暴露Authorization头
可选择以下任意一种方式配置:
方式一:全局CORS Bean(推荐)
在SecurityConfig类中添加CORS配置Bean,Spring Security会自动识别并加载:
@Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); // 替换为实际前端运行的源,生产环境改为正式前端域名 config.setAllowedOrigins(List.of("http://localhost:4200")); config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); config.setAllowedHeaders(List.of("*")); // 核心配置:将Authorization头暴露给前端JS config.setExposedHeaders(List.of("Authorization")); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; }
若使用Spring Boot 2.4以下版本,将
List.of(...)替换为Arrays.asList(...)即可。
方式二:Security配置内联规则
若不想单独声明Bean,可直接在configure(HttpSecurity http)方法中内联配置:
@Override protected void configure(HttpSecurity http) throws Exception { http.cors(cors -> cors.configurationSource(request -> { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("http://localhost:4200")); config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); config.setAllowedHeaders(List.of("*")); config.setExposedHeaders(List.of("Authorization")); config.setAllowCredentials(true); return config; })) // 保留原有安全配置 .authorizeRequests() .antMatchers("/user/register").permitAll() .anyRequest().authenticated() .and() .addFilterBefore(authFilter(), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(new JwtAuthorizationFilter(authenticationManagerBean(), userService), BasicAuthenticationFilter.class) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .exceptionHandling() .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)); // 仅保留CSRF禁用配置 http.csrf().disable(); }
可选优化
在MyAuthenticationSuccessHandler中补充响应编码配置,避免浏览器兼容问题:
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { String token = JWT.create().withSubject(((User) authentication.getPrincipal()).getUsername()) .withExpiresAt(new Date(System.currentTimeMillis() + SecurityConfig.expirationTime)) .sign(Algorithm.HMAC256(SecurityConfig.secret)); response.addHeader("Authorization", "Bearer " + token); // 新增以下两行 response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); }
配置生效后重启Spring后端,刷新Angular应用重新发起登录请求,即可正常读取Authorization响应头中的令牌。
内容的提问来源于stack exchange,提问作者Karol Wolny
相关产品推荐
相关产品推荐

