apisix网关ip-restriction插件使用说明

ip-restriction插件可以在网关层进行客户端请求ip拦截。

当然了,一般不推荐使用该方法,专业的事专业工具做。建议有条件,还是上防火墙或者waf来做。

官方文档:ip-restriction | Apache APISIX® -- Cloud-Native API Gateway

whitelist:白名单,配置允许访问的ip。

blacklist:黑名单,配置禁止访问的ip。

估计有朋友要问了,我上面那个external_auth的配置节干什么用的。

这个由于业务需要,我们做了一个动态校验请求。就是拦截后会请求这个链接,软如参数,然后如果返回200,就自动放通,如果返回其他状态,就拦截。

这个是自己写脚本实现的。代码如下,其实就是改了ip-restriction的脚本,增加了一个参数。

---
apiVersion: v1
data:
  init.lua: |
    --
    -- Licensed to the Apache Software Foundation (ASF) under one or more
    -- contributor license agreements.  See the NOTICE file distributed with
    -- this work for additional information regarding copyright ownership.
    -- The ASF licenses this file to You under the Apache License, Version 2.0
    -- (the "License"); you may not use this file except in compliance with
    -- the License.  You may obtain a copy of the License at
    --
    --     http://www.apache.org/licenses/LICENSE-2.0
    --
    -- Unless required by applicable law or agreed to in writing, software
    -- distributed under the License is distributed on an "AS IS" BASIS,
    -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    -- See the License for the specific language governing permissions and
    -- limitations under the License.
    --
    local ipairs    = ipairs
    local core      = require("apisix.core")
    local http   = require("resty.http")
    local lrucache  = core.lrucache.new({
        ttl = 300, count = 512
    })


    local schema = {
        type = "object",
        properties = {
            message = {
                type = "string",
                minLength = 1,
                maxLength = 1024,
                default = "Your IP address is not allowed"
            },
            whitelist = {
                type = "array",
                items = {anyOf = core.schema.ip_def},
                minItems = 1
            },
            blacklist = {
                type = "array",
                items = {anyOf = core.schema.ip_def},
                minItems = 1
            },
            external_auth = {
                type = "object",
                properties = {
                    uri = {type = "string"},
                    timeout = {
                        type = "integer",
                        minimum = 1,
                        maximum = 60000,
                        default = 3000,
                        description = "timeout in milliseconds",
                    },
                    method = {
                        type = "string",
                        default = "GET",
                        enum = {"GET", "POST"},
                        description = "the method for client to request the auth service"
                    },
                    headers = {type = "object"},
                    ip_param_key = {type = "string", default = "ip"},
                    allow_degradation = {type = "boolean", default = true},
                    rejected_code = {
                        type = "integer", minimum = 200, maximum = 599, default = 403
                    },
                    rejected_msg = {
                        type = "string", minLength = 1
                    }
                }
            }
        },
        anyOf = {
            {required = {"whitelist"}},
            {required = {"blacklist"}},
            {required = {"external_auth"}},
        }
    }


    local plugin_name = "ip-restriction"


    local _M = {
        version = 0.1,
        priority = 3000,
        name = plugin_name,
        schema = schema,
    }


    function _M.check_schema(conf)
        local ok, err = core.schema.check(schema, conf)

        if not ok then
            return false, err
        end

        -- we still need this as it is too complex to filter out all invalid IPv6 via regex
        if conf.whitelist then
            for _, cidr in ipairs(conf.whitelist) do
                if not core.ip.validate_cidr_or_ip(cidr) then
                    return false, "invalid ip address: " .. cidr
                end
            end
        end

        if conf.blacklist then
            for _, cidr in ipairs(conf.blacklist) do
                if not core.ip.validate_cidr_or_ip(cidr) then
                    return false, "invalid ip address: " .. cidr
                end
            end
        end

        return true
    end


    function _M.restrict(conf, ctx)
        local remote_addr = ctx.var.remote_addr

        local block = false
        if conf.blacklist then
            local matcher = lrucache(conf.blacklist, nil,
                                     core.ip.create_ip_matcher, conf.blacklist)
            if matcher then
                block = matcher:match(remote_addr)
            end
        end
        if block then
            -- 黑名单中的 ip 直接拒绝
            return 403, { message = conf.message }
        end

        local in_white = false
        if conf.whitelist then
            local matcher = lrucache(conf.whitelist, nil,
                                     core.ip.create_ip_matcher, conf.whitelist)
            if matcher then
                in_white = matcher:match(remote_addr)
            end
        end
        if in_white then
            -- 白名单中的 ip 直接放行
            return
        end

        if conf.external_auth then
            local external_auth = conf.external_auth
            local params = {
                method = external_auth.request_method
            }
            local httpc = http.new()
            httpc:set_timeout(external_auth.timeout)
            local uri = external_auth.ip_param_key .. '=' .. remote_addr
            if string.find(external_auth.uri, "?") then
                uri = external_auth.uri .. "&" .. uri
            else
                uri = external_auth.uri .. "?" .. uri
            end
            local res, err = httpc:request_uri(uri, params)
            -- 校验 ip 的服务不可用的时候
            if not res then
               core.log.error("failed to auth ip, err: ", err)
               if conf.external_auth.allow_degradation then
                   -- 允许放行
                   return
               else
                    return external_auth.rejected_code, { message = conf.message }
               end
            end
            -- 返回值为 2xx 的时候表示校验通过
            if res.status >= 300 then
                return external_auth.rejected_code, { message = conf.message }
            end
        end

    end


    return _M
kind: ConfigMap
metadata:
  name: ip-restriction
  namespace: apisix-szxc-qxz2v397g6
  resourceVersion: '224926381'

核心部分:

然后请求的接口,就可以自己编写了,相对更灵活。

对了,上面贴的是k8s的yaml,这是一个comfigmap,注入到apisix容器中,替换了原文件。

其实apisix的组件都是lua脚本实现的,很灵活,都可以根据需要自行重写。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/966448.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

uniapp 编译生成鸿蒙正式app步骤

1,在最新版本DevEco-Studio工具新建一个空项目并生成p12和csr文件(构建-生成私钥和证书请求文件) 2,华为开发者平台 根据上面生成的csr文件新增cer和p7b文件,分发布和测试 3,在最新版本DevEco-Studio工具 文…

在亚马逊云科技上云原生部署DeepSeek-R1模型(下)

在本系列的上篇中,我们介绍了如何通过Amazon Bedrock部署并测试使用了DeepSeek模型。在接下来的下篇中小李哥将继续介绍,如何利用亚马逊的AI模型训练平台SageMaker AI中的,Amazon Sagemaker JumpStart通过脚本轻松一键式部署DeepSeek预训练模…

A new release of pip is available: 24.2 -> 25.0

您可以使用官方提供的 get-pip.py 脚本来安装或升级pip。 1,下载 get-pip.py 脚本: curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py 2,运行脚本以安装或升级pip: python get-pip.py 3,实际运行效果

使用WebUI访问本地Deepseek(Ollama集成Open WebUI)

在《deepseek本地部署和使用(Linux虚拟机)》中,我们使用Ollama部署了Deepseek-r1,但是只能通过命令行方式交互,默认Ollama启动后,会启动一个监听到127.0.0.1,用以接收POST 请求,服务…

[NKU]C++安装环境 VScode

bilibili安装教程 vscode 关于C/C的环境配置全站最简单易懂!!大学生及初学初学C/C进!!!_哔哩哔哩_bilibili 1安装vscode和插件 汉化插件 ​ 2安装插件 2.1 C/C 2.2 C/C Compile run ​ 2.3 better C Syntax ​ 查看已…

DeepSeek图解10页PDF

以前一直在关注国内外的一些AI工具,包括文本型、图像类的一些AI实践,最近DeepSeek突然爆火,从互联网收集一些资料与大家一起分享学习。 本章节分享的文件为网上流传的DeepSeek图解10页PDF,免费附件链接给出。 1 本地 1 本地部…

如何将Excel的表格存为图片?

emmm,不知道题主具体的应用场景是什么,就分享几个我一般会用到的场景下奖excel表格保存为图片的技巧吧! 先来个总结: 方法 适用场景 画质 操作难度 截图(WinShiftS) 快速保存表格,方便粘贴…

UnrealEngine dotnet.exe 请求的操作需要提升 解决方案

一、问题如图 二、解决方式 按照图片路径找到dotnet.exe,鼠标右键-属性- 兼容性,勾选以管理员方式运行后重启UE。如下图:

活动预告 |【Part 1】Microsoft 安全在线技术公开课:通过扩展检测和响应抵御威胁

课程介绍 通过 Microsoft Learn 免费参加 Microsoft 安全在线技术公开课,掌握创造新机遇所需的技能,加快对 Microsoft Cloud 技术的了解。参加我们举办的“通过扩展检测和响应抵御威胁”技术公开课活动,了解如何更好地在 Microsoft 365 Defen…

「vue3-element-admin」告别 vite-plugin-svg-icons!用 @unocss/preset-icons 加载本地 SVG 图标

🚀 作者主页: 有来技术 🔥 开源项目: youlai-mall ︱vue3-element-admin︱youlai-boot︱vue-uniapp-template 🌺 仓库主页: GitCode︱ Gitee ︱ Github 💖 欢迎点赞 👍 收藏 ⭐评论 …

SAP HCM PFCG读取结构化权限参数

权限:HCM的权限分两套,一套是PFCG的普通权限,一套是结构化权限是根据组织ID限制访问权限的,今天我们讨论的话题如何把这两类的权限组合起来 场景:例如下载有个薪酬管理人员,他复制A和B部门,但是…

3D数字化营销:重塑家居电商新生态

随着电商的蓬勃发展,网上订购家具已成为众多消费者的首选。然而,线上选购家具的诸多挑战,如风格不匹配、尺寸不合适、定制效果不如预期以及退换货不便等,一直困扰着消费者。为解决这些问题,家居行业急需一种全新的展示…

发布:大彩科技DN系列2.8寸高性价比串口屏发布!

一、产品介绍 该产品是一款2.8寸的工业组态串口屏,采用2.8寸液晶屏,分辨率为240*320,支持电阻触摸、电容触摸、无触摸。可播放动画,带蜂鸣器,默认为RS232通讯电平,用户短接屏幕PCB上J5短接点即可切换为TTL电…

【C++篇】C++11新特性总结2

目录 1,可变参数模板 1.1,基本语法及原理 1.2,包扩展 4.3,emplace系列接口 2,新的类功能 2.1,默认的移动构造和移动赋值 2.2,default和delete 2.3,final与override 3&…

TCP三次握手全方面详解

文章目录 (1) 三次握手各状态CLOSE状态SYN_SENT状态SYN_RECV状态ESTABLISHED状态 (2) 为什么握手时的seqnum是随机值,以及acknum的功能(3) 三次握手中的半连接队列(SYN队列)和全连接队列(ACCEPT队列)半连接队列全连接队…

模拟开发小鹅通首页网站练习

HTML代码 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>小鹅通-首页</title><!-- 引入页…

认识O(NlogN)的排序

归并排序 归并排序&#xff08;任何一个递归&#xff09;如果不懂可以画一个树状结构去帮助自己去理解。 核心排序方法为Merger public class 归并排序 {public static void main(String[] args) {int[] arr1 {3, 1, 2, 2, 5, 6};int[] arr2 Arrays.copyOf(arr1, arr1.len…

Qt中的绘图设备:QPixmap、QImage 和 QPicture(详细图文教程_附代码)

&#x1f4aa; 图像算法工程师&#xff0c;专业从事且热爱图像处理&#xff0c;图像处理专栏更新如下&#x1f447;&#xff1a; &#x1f4dd;《图像去噪》 &#x1f4dd;《超分辨率重建》 &#x1f4dd;《语义分割》 &#x1f4dd;《风格迁移》 &#x1f4dd;《目标检测》 &a…

w199疫情打卡健康评测系统设计与实现

&#x1f64a;作者简介&#xff1a;多年一线开发工作经验&#xff0c;原创团队&#xff0c;分享技术代码帮助学生学习&#xff0c;独立完成自己的网站项目。 代码可以查看文章末尾⬇️联系方式获取&#xff0c;记得注明来意哦~&#x1f339;赠送计算机毕业设计600个选题excel文…

JAVA:Spring Boot 集成 Disruptor 的技术指南

1、简述 在高并发应用中&#xff0c;传统的队列机制如 BlockingQueue 在面对大量请求时容易成为系统瓶颈。而 LMAX Disruptor 是一个高效的无锁队列&#xff0c;适合用来构建高吞吐、低延迟的事件处理系统。本文将介绍如何在 Spring Boot 中集成 Disruptor&#xff0c;并列出详…