自定义Spring Cloud Gateweay局部过滤器

在项目中,我们可能会遇到,多个模块,不能的模块资源权限校验方式可能不一样,这个时候我们可以使用Gateway的局部过滤器来进行处理

我们需要自定义一个AbstractGatewayFilterFactory,代码如下:

@Component
public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<AuthGatewayFilterFactory.Config> {

    public AuthGatewayFilterFactory () {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerPath server = ServerPath.build(exchange);
            // url路径
            String path = server.getPath();
            ServerHttpRequest request = exchange.getRequest();
            HttpHeaders header = request.getHeaders();
        	String token = header.getFirst(Constants.AUTHORIZATION);
        	//todo 1:判断token是否有效,2:判断path是否在用户所在的资源中
            return chain.filter(exchange);
        };
    }

    public static class Config {
        //Put the configuration properties for your filter here
    }

}

然后我们需要在Gateway的yml中配置要权限校验的服务的过滤器即可

spring:
  cloud:
    gateway:
      routes:
        - id: auth
          uri: lb://auth
          predicates:
            - Path=/auth/**
          filters:
            - StripPrefix=1
            # 过滤器的名称取得是AuthGatewayFilterFactory去掉GatewayFilterFactory的部分
            - Auth

好了,到这里配置就基本结束了

最后,欢迎关注微信公众号一起交流


版权声明:本文为weixin_43834401原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。