Block Malicious IP from Accessing API
Block requests from specific IP addresses to secure APIs against attacks from banned IPs. It can be configured with a blacklist of IPs.
Prerequisite(s)
- Obtain a User Account with Super Admin or API Provider Role.
- Complete Add Service from API Definition.
Set Up Shared IP Blacklist for All APIs
Once you recognize a malicious IP is attacking one of you API, it is better to add this IP to a shared blacklist to prevent other APIs.
In this tutorial, you will enable ip-restriction
as global rule to build up a shared IP blacklist. If the IP is in the blacklist, the request is denied with a 403 error response. The IP address checked against the list could be the direct client IP or X-Forwarded-For address based on proxy levels.
- Select Plugins > Plugin Global Rules, then click Add Plugin Global Rules.
- Choose
ip-restriction
as the plugin. - Apply the following configuration to the JSON Editor. Add IP
127.0.0.1
to the blacklist:
{
"blacklist": ["127.0.0.1"],
"message": "Sorry, your IP address is not allowed."
}
.
- Click Add.
Validate
Send an API request:
curl -i http://127.0.0.1:9080/pet/1
Since the IP is restricted by the blacklist, at this point, you will see the expected API response.
HTTP/1.1 503 Service Temporarily Unavailable
Date: Fri, 01 Sep 2023 03:48:27 GMT
Content-Type: text/plain; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
X-RateLimit-Limit: 3
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 0
Server: APISIX/dev
{"error_msg":"Sorry, your IP address is not allowed."}