根据 IP 地址限制 API 访问
你可以根据 IP 地址配置访问控制,限制非预期用户访问 API。
本指南介绍如何在网关组上将 ip-restriction 插件配置为全局规则,以屏蔽黑名单中的 IP 地址。API7 网关会拒绝来自黑名单中 IP 地址的请求,并返回 403。请求的 IP 地址可以是实际客户端 IP 地址,也可以是 X-Forwarded-For 中的地址。
前提条件
为网关组配置 IP 地址限制
发现恶意访问者后,将其 IP 地址添加到黑名单,限制其访问你的 API。
- 控制台
- ADC
- Ingress Controller
-
从侧边栏选择网关组的插件设置。
-
选择插件全局规则,然后点击启用插件。
-
搜索
ip-restriction插件,然后点击启用。 -
在对话框中完成以下操作。
-
将以下配置添加到 JSON 编辑器,把 IP 地址
127.0.0.1添加到黑名单。{"blacklist": ["127.0.0.1"],"message": "Sorry, your IP address is not allowed."} -
点击启用。
-
要使用 ADC 配置 IP 限制,请创建以下配置:
adc.yaml
services:
- name: httpbin API
upstream:
name: default
scheme: http
nodes:
- host: httpbin.org
port: 80
weight: 100
routes:
- uris:
- /ip
name: security-ip
methods:
- GET
global_rules:
ip-restriction:
_meta:
disable: false
blacklist:
- 127.0.0.1
message: Sorry, your IP address is not allowed.
将配置同步到 API7 网关:
adc sync -f adc.yaml
创建路由的 Kubernetes 清单文件:
httpbin-route.yaml
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
name: httpbin-route
# namespace: api7 # replace with your namespace
spec:
http:
- name: httpbin-route
match:
paths:
- /ip
methods:
- GET
backends:
- serviceName: httpbin
servicePort: 80
创建另一个清单文件,将 ip-restriction 插件配置为全局规则:
global-ip-restriction.yaml
apiVersion: apisix.apache.org/v2
kind: ApisixGlobalRule
metadata:
name: global-ip-restriction
# namespace: api7 # replace with your namespace
spec:
plugins:
- name: ip-restriction
enable: true
config:
blacklist:
- "127.0.0.1"
message: Sorry, your IP address is not allowed.
将配置应用到你的集群:
kubectl apply -f httpbin-route.yaml -f global-ip-restriction.yaml
验证
从受限的 IP 地址发送请求。在本例中,127.0.0.1 被配置为黑名单 IP 地址:
curl -i "http://127.0.0.1:9080/ip"
你会收到 403 Forbidden 响应和以下消息:
{"error_msg":"Sorry, your IP address is not allowed."}