关于 springcloud gateway 设置 context-path 的问题

大家好,我是烤鸭:

      今天说一下遇到的问题,关于 springcloud gateway 设置 context-path 的问题。


1.  使用场景


由于没有申请二级域名,网关使用的地址是 xxx.com/gateway/ 用nginx转发的时候 /gateway/ 也被用来寻址。
gateway 没办法设置 context-path ,针对我这个场景有3个解决方案。

2.  解决方案


2.1 增加本地路由(有一个网址指向自己,这里就是 /gateway)

spring:
  cloud:
    gateway:
      routes:
      # 网关本身没有contextPath,通过自己转发自己,达到能处理contextPath
      - id: self
        uri: http://localhost:${server.port}
        predicates:
        - Path=/${spring.application.name}/**
        filters:
        - StripPrefix=1
        order: -11000

这种方式会丢失请求,暂时没考虑原因,就pass了。

2.2 增加过滤器,改写路径


ApiFilter.java

package com.yiche.ballast.filter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.WebFilter;
import reactor.core.publisher.Mono;


@Configuration
public class ApiFilter {
    @Value("${spring.cloud.gateway.api-prefix:/gateway}")
    private String prefix;

    @Bean
    @Order(-1)
    public WebFilter apiPrefixFilter() {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();

            String path = request.getURI().getRawPath();
            if (!path.contains(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(prefix, "");
            ServerHttpRequest newRequest = request.mutate().path(newPath).build();

            return chain.filter(exchange.mutate().request(newRequest).build());
        };
    }
}


这样/gateway 请求进来之后,转发到routers 的时候会把 /gateway去掉,缺点是每个请求进来都需要对路径处理一次。
能配置的尽量不写代码。

2.3 修改配置,在所有的router路径前加前缀(这里就是都加上 /gateway)

spring:
    cloud:
        gateway:
            routes:
            - id: api-route
              filters:
                - StripPrefix=1
              predicates:
                - name: Path
                  args[pattern]: /gateway/api/**
              uri: lb://xxx-api

偷懒的做法,路由多的时候也挺难受。

现在路由不多,选择了第三种方式。看各自的场景选择吧。

以下是一个简单的 Spring Cloud Gateway 基于JWT的验证代码案例: 1. 首先,确保你的项目中已经引入了相关的依赖,包括 Spring Cloud GatewaySpring Security 和 JWT 相关的库。 2. 创建一个自定义的 GatewayFilter,用于验证JWT并将用户身份信息添加到请求头中: ```java import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; @Component public class JwtAuthFilter implements GatewayFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // 从请求头中获取 JWT String jwt = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION); // 验证 JWT,根据需要进行相应的验证逻辑 // 如果验证成功,将用户身份信息添加到请求头中 exchange.getRequest().mutate() .header("X-User-Id", "123") // 示例,替换为实际的用户身份信息 .build(); return chain.filter(exchange); } } ``` 3. 在配置类中注册自定义的 GatewayFilter: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class GatewayConfig { @Bean public JwtAuthFilter jwtAuthFilter() { return new JwtAuthFilter(); } } ``` 4. 配置 Spring Cloud Gateway 路由谓词和过滤器,指定需要进行JWT验证的路由: ```yaml spring: cloud: gateway: routes: - id: example_route uri: http://example.com predicates: - Path=/example/** filters: - JwtAuthFilter= # 指定使用 JwtAuthFilter 进行JWT验证 ``` 在这个示例中,我们创建了一个名为 `JwtAuthFilter` 的自定义过滤器,用于验证JWT并将用户身份信息添加到请求头中。然后在配置类中注册该过滤器,并在路由配置中指定需要使用该过滤器的路由。 请注意,这只是一个简单的示例,实际的JWT验证逻辑可能更复杂。你可以根据自己的需求进行相应的调整和扩展。希望对你有所帮助!
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烤鸭的世界我们不懂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值