Spring Cloud Gateway设置context-path后cookie丢失
在gateway中不支持设置context-path,可以通过两种方式设置context-path
-
设置全局过滤器,拦截请求,修改转发的路径。
@Configuration public class GatewayPrefixHandler { private final String GATEWAY_PREFIX = "/api"; @Bean @Order(-1) public WebFilter gatewayPrefixFilter() { return (exchange, chain) -> { ServerHttpRequest request = exchange.getRequest(); String path = request.getURI().getRawPath(); if (!path.contains(GATEWAY_PREFIX)) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.BAD_GATEWAY); DataBuffer buffer = response .bufferFactory() .wrap(HttpStatus.BAD_GATEWAY.getReasonPhrase().getBytes()); return response.writeWith(Mono.just(buffer)); } String newPath = path.replaceFirst(GATEWAY_PREFIX, ""); ServerHttpRequest newRequest = request.mutate().path(newPath).build(); return chain.filter(exchange.mutate().request(newRequest).build()); }; } }
-
在route定义中手动添加context-path,通过过滤器工厂转发时候去掉前缀
spring: cloud: gateway: context-path: /api # 自定义属性 routes: - id: common-service uri: lb://common-service # lb: 负载均衡 predicates: - Path=${spring.cloud.gateway.context-path}/common/** filters: - StripPrefix=1 # 转发路由时候去掉/api
-
通过上面两种方法设置context-path后,会存在cookie丢失情况
具体表现是在set-cookie响应头会有Path=子服务的context-path, 导致设置不上cookie
解决方案: 修改set-cookie的Path=/,只需要在各个子服务加上设置path的配置
server:
servlet:
session:
cookie:
http-only: false
path: / # 解决gateway设置context-path后,session设置不成功问题