限制 IP 地址访问 API
你可以基于 IP 地址配置访问控制,以防止不必要的用户访问你的 API。
本指南将引导你在网关组上将 ip-restriction 插件配置为全局规则,以阻止黑名单中的 IP 地址。如果请求来自黑名单中的 IP 地址,API7 网关将拒绝该请求并返回 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 # 替换为你的命名空间
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 # 替换为你的命名空间
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."}