限制访问 API 的 IP 地址
你可以基于 IP 地址配置访问控制,以防止不受欢迎的用户访问你的 API。
本指南将引导你在网关组上将 ip-restriction 插件配置为全局规则,以阻止黑名单中的 IP 地址。如果请求来自黑名单中的 IP 地址,API7 网关将拒绝该请求并返回 403 响应码。请求的 IP 地址可以是实际的客户端 IP 地址,也可以是 X-Forwarded-For 地址。
先决条件
在网关组上配置 IP 地址限制
当识别出恶意攻击者时,将他们的 IP 地址添加到黑名单中以限制他们访问你的 API。
- Dashboard
- ADC
- Ingress Controller
- 从侧边导航栏选择网关组的 插件设置。
- 选择 插件全局规则,然后点击 新增插件。
- 搜索
ip-restriction插件,然后点击 新增。 - 在对话框中,执行以下操作:
-
将以下配置添加到 JSON Editor 以将 IP 地址
127.0.0.1添加到黑名单中:{
"blacklist": ["127.0.0.1"],
"message": "Sorry, your IP address is not allowed."
} -
点击 新增。
若要使用 ADC 配置该插件,请创建以下配置:
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
- Gateway API
- APISIX CRD
更新你的 GatewayProxy 清单以将 ip-restriction 启用为全局插件:
gateway-proxy.yaml
apiVersion: apisix.apache.org/v1alpha1
kind: GatewayProxy
metadata:
namespace: api7
name: apisix
spec:
provider:
type: ControlPlane
controlPlane:
endpoints:
- https://xxx.xxx.xxx.xxx:7443 # 用你的 CP 端点进行更新
auth:
type: AdminKey
adminKey:
value: xxxxxxxxxxx # 用你的 Admin key 进行更新
plugins:
- name: ip-restriction
enabled: true
config:
blacklist:
- 127.0.0.1
message: Sorry, your IP address is not allowed.
为路由创建一个 Kubernetes 清单文件:
httpbin-route.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: api7
name: get-ip
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /ip
将配置应用到你的集群:
kubectl apply -f gateway-proxy.yaml -f httpbin-route.yaml
为全局的 ip-restriction 插件创建一个 Kubernetes 清单文件:
global-ip-restriction.yaml
apiVersion: apisix.apache.org/v2
kind: ApisixGlobalRule
metadata:
namespace: api7
name: global-ip-restriction
spec:
ingressClassName: apisix
plugins:
- name: ip-restriction
enable: true
config:
blacklist:
- "127.0.0.1"
message: Sorry, your IP address is not allowed.
为路由创建一个 Kubernetes 清单文件:
httpbin-route.yaml
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: api7
name: httpbin
spec:
ingressClassName: apisix
http:
- name: get-ip
match:
paths:
- /ip
backends:
- serviceName: httpbin
servicePort: 80
将配置应用到你的集群:
kubectl apply -f global-ip-restriction.yaml -f httpbin-route.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."}