限制访问 API 的 IP 地址
你可以基于 IP 地址配置访问控制,阻止非预期用户访问 API。
本指南介绍如何在网关组上将 ip-restriction 插件配置为全局规则,以拦截黑名单中的 IP 地址。如果请求来自黑名单中的 IP 地址,API7 网关会以 403 响应码拒绝请求。请求 IP 地址可以是客户端的实际 IP 地址,也可以是 X-Forwarded-For 地址。
前提条件
为网关组内所有 API 设置共享 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 配置插件时,创建以下配置。
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 # 更新为你的控制面端点
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."}