Restrict IP Addresses from APIs
You can configure access controls based on IP addresses to prevent unwanted users from accessing your APIs.
This guide will walk you through configuring the ip-restriction
plugin on a gateway group as a global rule, to block IP addresses in a blacklist. If a request comes from an IP address in the blacklist, the API7 Gateway will deny the request with a 403
response code. The IP address of the request can be either the actual client IP address or the X-Forwarded-For
address.
Prerequisite(s)
Configure IP Address Restriction on a Gateway Group
When malicious actors are identified, add their IP addresses to the blacklist to restrict their access to your APIs.
- Dashboard
- ADC
- Ingress Controller
- Select Plugin Settings of your the gateway group from the side navigation bar.
- Select Plugin Global Rules, then click Enable Plugin.
- Search for the
ip-restriction
plugin, then click Enable. - In the dialog box, do the following:
Add the following configuration to the JSON Editor to add the IP address
127.0.0.1
to the blacklist:{
"blacklist": ["127.0.0.1"],
"message": "Sorry, your IP address is not allowed."
}Click Enable.
To use ADC to configure the plugin, create the following configuration:
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.
Synchronize the configuration to API7 Gateway:
adc sync -f adc.yaml
Create a Kubernetes manifest file for a route:
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
Create another manifest file for a global ip-restriction
plugin:
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.
Apply the configurations to your cluster:
kubectl apply -f httpbin-route.yaml -f global-ip-restriction.yaml
Validate
Send a request from the restricted IP address. For this example, 127.0.0.1
was configured as a blacklisted IP address:
curl -i "http://127.0.0.1:9080/ip"
You will receive a 503 Service Temporarily Unavailable
response with the following message:
{"error_msg":"Sorry, your IP address is not allowed."}