修改后的X-Authorization Cookie无法到达Spring Cloud Gateway排查
问题背景
开发WebSocket项目时,计划通过X-Authorization Cookie传递授权Token,实现客户端设置Cookie、网关转发后下游服务提取Token的授权流程。本地环境运行正常,但部署到Azure VM后,该Cookie未到达Spring Cloud Gateway,疑似中途丢失。
实现代码
1. TypeScript客户端实现
async connectToWebSocket():Promise<void> { const token = await this.keycloakService.getToken(); this.cookieService.set('X-Authorization', token); this.socket = new WebSocket("ws://url_address:8080/path"); }
2. Java下游服务过滤器实现
@Override protected void doFilterInternal(@NotNull HttpServletRequest request,@NotNull HttpServletResponse response,@NotNull FilterChain filterChain) throws ServletException, IOException { log.info("Filtering request"); String token = extractTokenFromRequest(request); log.info("extracted token"); if (StringUtils.hasText(token)) { log.info("Passing to next filter"); filterChain.doFilter(new TokenHttpServletRequestWrapper(request, token), response); } else { throw new TokenRetrieveException("No token provided", HttpStatus.UNAUTHORIZED); } } private String extractTokenFromRequest(HttpServletRequest request) { log.info("getting cookie"); Cookie[] cookies = request.getCookies(); if (cookies != null) { log.info("cookie not null"); Optional<Cookie> tokenCookie = Arrays.stream(cookies) .filter(cookie -> "X-Authorization".equals(cookie.getName())) .findFirst(); if (tokenCookie.isPresent()) { return tokenCookie.get().getValue(); } } return null; }
问题现象
- 本地使用
localhost:8080通过Docker Compose启动服务时,X-AuthorizationCookie可正常传递至Spring Cloud Gateway及下游服务,授权流程运行无异常。 - 将服务部署到Azure VM并使用服务器地址启动后,客户端发送相同请求,
X-AuthorizationCookie未到达Spring Cloud Gateway,下游服务抛出No token provided未授权异常。
排查方向
- Cookie属性配置检查:
- 本地localhost为同源环境,浏览器默认规则允许携带Cookie;跨域场景下若未设置
SameSite=None; Secure(若使用HTTPS),浏览器可能拦截Cookie传递。 - 未指定
Domain时,Cookie默认绑定当前域名,若服务器地址与客户端域名不符,请求时不会携带该Cookie。
- 本地localhost为同源环境,浏览器默认规则允许携带Cookie;跨域场景下若未设置
- 跨域请求规则验证:
- 确认Spring Cloud Gateway是否配置了正确的CORS规则,开启
allowCredentials=true允许携带凭证。 - 检查WebSocket连接是否符合跨域携带Cookie的要求,部分场景下需确保客户端请求明确携带凭证。
- 确认Spring Cloud Gateway是否配置了正确的CORS规则,开启
- Docker网络配置排查:
- 检查Azure VM上Docker Compose的网络配置,确认端口映射正确,网关服务能完整接收客户端请求的所有Header和Cookie。
- 网关过滤规则检查:
- 排查Spring Cloud Gateway的路由配置,是否存在移除Cookie的过滤器或规则,导致
X-AuthorizationCookie被丢弃。
- 排查Spring Cloud Gateway的路由配置,是否存在移除Cookie的过滤器或规则,导致
- 日志验证:
- 在Spring Cloud Gateway层添加详细日志,打印所有请求的Cookie列表,确认Cookie是否真的未到达;同时在客户端浏览器调试工具中检查Cookie是否成功设置,且请求时确实携带了该Cookie。
- Azure网络配置检查:
- 检查Azure VM的网络安全组(NSG)是否有拦截规则,或是否存在代理服务器修改了请求头和Cookie。
内容的提问来源于stack exchange,提问作者Fellou98
相关产品推荐
相关产品推荐

