当前位置: 代码网 > it编程>编程语言>Java > spring-gateway filters添加自定义过滤器实现流程分析(可插拔)

spring-gateway filters添加自定义过滤器实现流程分析(可插拔)

2025年05月28日 Java 我要评论
需求背景公司要求,通过公司网络代理访问的请求需要做请求隔离,即,通过特定代理ip访问的请求,需要除正常权限以外,还需要对请求路径,及特定路径下的请求参数做校验,通过校验正常访问,否则拒绝通过代理ip的

需求背景

公司要求,通过公司网络代理访问的请求需要做请求隔离,即,通过特定代理ip访问的请求,需要除正常权限以外,还需要对请求路径,及特定路径下的请求参数做校验,通过校验正常访问,否则拒绝通过代理ip的请求。

需求拆解

1.针对特定的服务做限制;

2.特定的代理ip来源请求做校验;

3.特定的请求接口做限制;

4.特定的接口的特定的请求参数值做校验;

大致可以细分如上四点,在网关层统一实现需求,参考spring-gateway过滤器原理,个性化一个过滤器,按需配置即可;

设计流程及作用域

在配置网关路由策略时按需配置,灵活使用。

图2.1过滤器位置

自定义过滤器名称:internalvalidator

2.2spring-gateway使用配置示例

过滤器设计

1.name : internalvalidator 过滤器id (必须)

2.args : 过滤器参数 (个性化实现时必须)

2.1 paths: /api/**,/** 请求路径校验(通配符),前提条件1

2.2 limited-from: '172.24.173.62,172.24.172.252' 模拟代理ip地址,前提条件2

2.3 conditions: 条件过滤,这是个个性化配置集合

2.3.1 paths: /api/** 条件集合判断路径校验(通配符)

2.3.2 body-param: 'code' 请求体参数名{'code':'159300'}

2.3.3 body-value:'159300' 参数名对应的参数值

2.3.4 path-param: 'name' 路径参数名 ?name=zhangsan

2.3.5 path-value: 'zhangsan' 路径参数值 

3.excludes:'/api/login/*' 排除路径(通配符)

逻辑处理

1.来自代理ip判断

3.1逻辑处理

逻辑流程

3.2流程处理

代码逻辑

1.名称必须是internalvalidator + gatewayfilterfactory

2.config服从驼峰命名转换 即limited-from : limitedfrom

3.对config映射属性必须要有set方法

@component
@slf4j
public class internalvalidatorgatewayfilterfactory extends abstractgatewayfilterfactory<internalvalidatorgatewayfilterfactory.config> implements ordered {
    private final antpathmatcher antpathmatcher = new antpathmatcher();
    public internalvalidatorgatewayfilterfactory() {
        super(config.class); // 指定配置类
    }
    @override
    public gatewayfilter apply(config config) {
        return (exchange, chain) -> {
            set<string> limitedips = config.getlimitedips();
            serverhttprequest request = exchange.getrequest();
            //接口路径
            string clientip = iphelp.getclientip(request);
            if (!islimitedip(clientip, limitedips)) {
                return chain.filter(exchange);
            }
            string path = request.getpath().value();
            set<string> includespaths = config.getincludespaths();
            if (!pathmatch(path, includespaths)) {
                log.info(" --> includespaths: {}, 不包含: 请求路径:{},", includespaths, path);
                return chain.filter(exchange);
            }
            set<string> excludespaths = config.getexcludespaths();
            if (pathmatch(path, excludespaths)) {
                log.info(" --> excludespaths: {}, contains: 请求路径:{},", excludespaths, path);
                return chain.filter(exchange);
            }
            map<string, map<string, string>> pathparamvaluemap = config.getpathparamvaluemap();
            map<string, map<string, string>> bodyparamvaluemap = config.getbodyparamvaluemap();
            map<string, string> bodyparammap = getpathparamvaluemap(path, bodyparamvaluemap);
            map<string, string> queryparammap = getpathparamvaluemap(path, pathparamvaluemap);
            if ((bodyparammap == null || bodyparammap.isempty()) && (
                    queryparammap == null || queryparammap.isempty()
            )) {
                exchange.getresponse().setstatuscode(httpstatus.forbidden);
                return exchange.getresponse().setcomplete();
            }
            if (queryparammap != null && !queryparammap.isempty()) {
                multivaluemap<string, string> queryparams = request.getqueryparams();
                if (!queryparammatch(queryparammap, queryparams)) {
                    log.info(" --> path: {}, bodyparamconditions: {}, queryparammap: {},校验失败!", path, bodyparammap, queryparammap);
                    exchange.getresponse().setstatuscode(httpstatus.forbidden);
                    return exchange.getresponse().setcomplete();
                }
                if (bodyparammap == null || bodyparammap.isempty()) {
                    return chain.filter(exchange);
                }
            }
            if (bodyparammap != null && !bodyparammap.isempty()) {
                string method = request.getmethodvalue();
                if ("post".equals(method)) {
                    return databufferutils.join(exchange.getrequest().getbody())
                            .flatmap(databuffer -> {
                                byte[] bytes = new byte[databuffer.readablebytecount()];
                                databuffer.read(bytes);
                                try {
                                    string bodystring = new string(bytes, "utf-8");
                                    if (!bodyparammatch(bodyparammap, bodystring)) {
                                        exchange.getresponse().setstatuscode(httpstatus.forbidden);
                                        return exchange.getresponse().setcomplete();
                                    }
                                } catch (unsupportedencodingexception e) {
                                }
                                databufferutils.release(databuffer);
                                flux<databuffer> cachedflux = flux.defer(() -> {
                                    databuffer buffer = exchange.getresponse().bufferfactory()
                                            .wrap(bytes);
                                    return mono.just(buffer);
                                });
                                serverhttprequest mutatedrequest = new serverhttprequestdecorator(
                                        exchange.getrequest()) {
                                    @override
                                    public flux<databuffer> getbody() {
                                        return cachedflux;
                                    }
                                };
                                return chain.filter(exchange.mutate().request(mutatedrequest).build());
                            });
                }
            }
            exchange.getresponse().setstatuscode(httpstatus.forbidden);
            return exchange.getresponse().setcomplete();
        };
    }
    @override
    public int getorder() {
        return 2;
    }
    private map<string, string> getpathparamvaluemap(string path, map<string, map<string, string>> paramvaluemap) {
        if (paramvaluemap == null || paramvaluemap.isempty()) {
            return null;
        }
        map<string, string> res = new hashmap<>();
        for (map.entry<string, map<string, string>> paramvalueentry : paramvaluemap.entryset()) {
            string pathpredicate = paramvalueentry.getkey();
            if (antpathmatcher.match(pathpredicate, path)) {
                map<string, string> paramvalue = paramvalueentry.getvalue();
                if (paramvalue == null) {
                    continue;
                }
                res.putall(paramvalue);
            }
        }
        return res;
    }
    private string extractparam(string jsonstr, string key) {
        try {
            int startindex = jsonstr.indexof("\"" + key + "\"");
            if (startindex != -1) {
                int valuestart = jsonstr.indexof(':', startindex);
                int valueend = jsonstr.indexof(',', valuestart);
                if (valueend == -1) {
                    valueend = jsonstr.indexof('}', valuestart);
                }
                if (valuestart != -1 && valueend != -1) {
                    string valuepart = jsonstr.substring(valuestart + 1, valueend).trim();
                    return valuepart.replaceall("\"", "");
                }
            }
        } catch (exception e) {
            // 可以记录日志
            return null;
        }
        return null;
    }
    private boolean pathmatch(string path, set<string> predicatepaths) {
        if (predicatepaths == null || predicatepaths.isempty()) {
            return false;
        }
        return predicatepaths.stream()
                .anymatch(predicatepath -> antpathmatcher.match(predicatepath, path));
    }
    private boolean parammatch(map<string, string> bodyparammap,
                               map<string, string> queryparammap,
                               serverhttprequest request,
                               serverwebexchange exchange
    ) {
        return true;
    }
    private boolean bodyparammatch(map<string, string> bodyparamconditions, string bodystr) {
        if (bodystr == null) {
            return false;
        }
        for (map.entry<string, string> conditionmapentry : bodyparamconditions.entryset()) {
            string predicateparam = conditionmapentry.getkey();
            string predicatevalue = conditionmapentry.getvalue();
            string acvalue = extractparam(bodystr, predicateparam);
            if (!predicatevalue.equals(acvalue)) {
                log.info(" --> bodyparammatch:::predicateparam:{}, predicatevalue:{}, acvalue:{},参数校验不通过!",
                        predicateparam, predicatevalue, acvalue);
                return false;
            }
        }
        return true;
    }
    private boolean queryparammatch(map<string, string> conditionmap, multivaluemap<string, string> queryparams) {
        for (map.entry<string, string> conditionmapentry : conditionmap.entryset()) {
            string predicateparam = conditionmapentry.getkey();
            string predicatevalue = conditionmapentry.getvalue();
            string acvalue = queryparams.getfirst(predicateparam);
            if (!predicatevalue.equals(acvalue)) {
                log.info(" --> queryparammatch:::predicateparam:{}, predicatevalue:{}, acvalue:{},参数校验不通过!",
                        predicateparam, predicatevalue, acvalue);
                return false;
            }
        }
        return true;
    }
    private boolean islimitedip(string clientip, set<string> limitedips) {
        if (clientip == null || clientip.isempty()) {
            log.warn(" --> clientip:{} 为空!", clientip);
            return true;
        }
        if (limitedips == null || limitedips.isempty()) {
            log.info(" --> limitedips:{} 为空!", limitedips);
            return false;
        }
        for (string limitedip : limitedips) {
            if (clientip.contains(limitedip)) {
                return true;
            }
        }
        return false;
    }
    // 配置类
    public static class config {
        private string paths = "/**";
        private string limitedfrom;
        private list<conditionconfig> conditions = new arraylist<>();
        private string excludes;
        private set<string> includespaths;
        private set<string> limitedips = new hashset<>();
        private set<string> excludespaths = new hashset<>();
        private map<string, map<string, string>> bodyparamvaluemap = new hashmap<>();
        private map<string, map<string, string>> pathparamvaluemap = new hashmap<>();
        public void setpaths(string paths) {
            this.paths = paths;
            if (paths != null) {
                this.includespaths = new hashset<>(arrays.aslist(paths.split(",")));
            }
        }
        public void setlimitedfrom(string limitedfrom) {
            this.limitedfrom = limitedfrom;
            if (limitedfrom != null) {
                this.limitedips = new hashset<>(arrays.aslist(limitedfrom.split(",")));
            }
        }
        public void setconditions(list<conditionconfig> conditions) {
            this.conditions = conditions;
            if (conditions != null && !conditions.isempty()) {
                for (conditionconfig condition : conditions) {
                    string conditionpaths = condition.getpaths();
                    string bodyparam = condition.getbodyparam();
                    string bodyvalue = condition.getbodyvalue();
                    string pathparam = condition.getpathparam();
                    string pathvalue = condition.getpathvalue();
                    if (conditionpaths != null) {
                        if (bodyparam != null && bodyvalue != null) {
                            for (string path : conditionpaths.split(",")) {
                                map<string, string> bodyparamcondition = bodyparamvaluemap.get(path);
                                if (bodyparamcondition == null) {
                                    bodyparamcondition = new hashmap<>();
                                }
                                bodyparamcondition.put(bodyparam, bodyvalue);
                                bodyparamvaluemap.put(path, bodyparamcondition);
                            }
                        }
                        if (pathparam != null && pathvalue != null) {
                            for (string path : conditionpaths.split(",")) {
                                map<string, string> pathparamcondition = pathparamvaluemap.get(path);
                                if (pathparamcondition == null) {
                                    pathparamcondition = new hashmap<>();
                                }
                                pathparamcondition.put(pathparam, pathvalue);
                                pathparamvaluemap.put(path, pathparamcondition);
                            }
                        }
                    }
                }
            }
        }
        public void setexcludes(string excludes) {
            this.excludes = excludes;
            if (excludes != null) {
                this.excludespaths = new hashset<>(arrays.aslist(excludes.split(",")));
            }
        }
        public set<string> getincludespaths() {
            return includespaths;
        }
        public set<string> getlimitedips() {
            return limitedips;
        }
        public set<string> getexcludespaths() {
            return excludespaths;
        }
        public map<string, map<string, string>> getbodyparamvaluemap() {
            return bodyparamvaluemap;
        }
        public map<string, map<string, string>> getpathparamvaluemap() {
            return pathparamvaluemap;
        }
    }
    @data
    public static class conditionconfig {
        private string paths;
        private string bodyparam;
        private string bodyvalue;
        private string pathparam;
        private string pathvalue;
    }
}

借助了工具类iphelp.java

import lombok.extern.slf4j.slf4j;
import org.springframework.http.httpheaders;
import org.springframework.http.server.reactive.serverhttprequest;
import java.net.inetsocketaddress;
import java.util.arrays;
import java.util.collections;
import java.util.list;
@slf4j
public class iphelp {
    private static final list<string> ip_headers = collections.unmodifiablelist(arrays.aslist(
            "x-forwarded-for",
            "x-forwarded-for",
            "xff",
            "x-real-ip",
            "proxy-client-ip",
            "wl-proxy-client-ip",
            "http_client_ip",
            "http_x_forwarded_for"
    ));
    public static string getclientip(serverhttprequest request) {
        string resultip = null;
        httpheaders headers = request.getheaders();
        for (string head : ip_headers) {
            string ip = headers.getfirst(head);
            log.info(" --> ip_header:{}, ip_value:{}", head, ip);
            if (isvalidip(ip)) {
                resultip = ip;
                break;
            }
        }
        if (resultip == null && request.getremoteaddress() != null) {
            inetsocketaddress remoteaddress = request.getremoteaddress();
            resultip = remoteaddress.getaddress().gethostaddress();
            log.info(" --> ip_header: remoteaddress, ip_value:{}", resultip);
        }
        log.info(" --> getclientip, ip_value:{}", resultip);
        return resultip;
    }
    private static boolean isvalidip(string ip) {
        return ip != null && !ip.trim().isempty() && !"unknown".equalsignorecase(ip.trim());
    }
}

respect!

到此这篇关于spring-gateway filters添加自定义过滤器实现(可插拔)的文章就介绍到这了,更多相关spring-gateway filters自定义过滤器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com