Angular开发环境(ng serve)下Spring Security Session失效问题
问题定位与修复方案
跨域场景下Spring Session失效,核心原因是CORS配置冲突和Cookie跨域传输限制导致Session ID无法在前后端之间正确传递。以下是具体排查和修复步骤:
1. 修正CORS配置逻辑
你的CORS配置中,applyPermitDefaultValues()会先设置默认规则(比如allowedOrigins = *),再与自定义配置合并,这会和allowCredentials=true产生冲突(浏览器禁止同时使用通配符源和允许凭证)。调整配置顺序,直接基于自定义规则构建:
@Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowCredentials(true); configuration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.HEAD.name(), HttpMethod.POST.name(), HttpMethod.OPTIONS.name())); configuration.setAllowedHeaders(Collections.singletonList("*")); configuration.setExposedHeaders(Collections.singletonList("*")); configuration.setAllowedOrigins(Collections.singletonList("http://localhost:4200")); // 移除applyPermitDefaultValues,避免覆盖自定义配置 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; }
2. 调整Cookie跨域属性
跨域请求时,默认的JSESSIONID Cookie的SameSite属性为Lax,浏览器不会在跨域POST请求中携带该Cookie。需要修改Spring Session的Cookie配置:
@Bean public CookieSerializer cookieSerializer() { DefaultCookieSerializer serializer = new DefaultCookieSerializer(); serializer.setSameSite("None"); // 本地HTTP开发环境下关闭Secure,生产环境必须开启 serializer.setUseSecureCookie(false); serializer.setCookieName("JSESSIONID"); serializer.setDomainName("localhost"); return serializer; }
3. 验证前端与后端的Session传递
- 前端请求已设置
withCredentials: true,确保请求目标是后端完整地址(如http://localhost:8080/api/csv),若使用Angular代理,需在代理配置中添加"withCredentials": true - 重启服务后,完成认证流程,通过浏览器开发者工具:
- 查看Network面板中认证请求的响应头,确认存在
Set-Cookie: JSESSIONID=xxx; ... - 查看Application面板→Cookies→
http://localhost:8080下是否保存了JSESSIONID - 发起问题中的POST请求,检查请求头是否携带
Cookie: JSESSIONID=xxx
- 查看Network面板中认证请求的响应头,确认存在
4. 确认Session创建策略
你的sessionCreationPolicy设置为ALWAYS,会强制创建Session,此配置无问题。可通过后端日志验证:认证成功后是否生成Session,后续请求携带的Session ID是否与认证时一致。
内容的提问来源于stack exchange,提问作者Bruno Miguel
相关产品推荐
相关产品推荐

