Spring Cloud Gateway设置context-path后cookie丢失

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设置不成功问题
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值