API7 Docs
Security

IP Restriction

The ip-restriction plugin restricts access to upstream resources based on an IP address whitelist or blacklist, improving API security.

The ip-restriction plugin supports restricting access to upstream resources by IP addresses, through either configuring a whitelist or blacklist of IP addresses. Restricting IP to resources helps prevent unauthorized access and harden API security.

Examples

The examples below demonstrate how you can configure the ip-restriction plugin for different scenarios.

Restrict Access by Whitelisting

The following example demonstrates how you can whitelist a list of IP addresses that should have access to the upstream resource and customize the error message for access denial.

Create a route with the ip-restriction plugin as such:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
  -H "X-API-KEY: ${ADMIN_API_KEY}" \
  -d '{
    "id": "ip-restriction-route",
    "uri": "/anything",
    "plugins": {
      "ip-restriction": {
        "whitelist": [
          "192.168.0.1/24"
        ],
        "message": "Access denied"
      }
    },
    "upstream": {
      "type": "roundrobin",
      "nodes": {
        "httpbin.org:80": 1
      }
    }
  }'

❶ Replace with the IP addresses you would like to whitelist.

❷ Customize the error message for when the access is denied.

Send a request to the route:

curl -i "http://127.0.0.1:9080/anything"

If your IP is allowed, you should receive an HTTP/1.1 200 OK response. If not, you should receive an HTTP/1.1 403 Forbidden response with the following error message:

{"message":"Access denied"}

Restrict Access Using Modified IP

The following example demonstrates how you can modify the IP used for IP restriction, using the real-ip plugin. This is particularly useful if APISIX is behind a reverse proxy and the real client IP is not available to APISIX.

Create a route as follows:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
  -H "X-API-KEY: ${ADMIN_API_KEY}" \
  -d '{
    "id": "ip-restriction-route",
    "uri": "/anything",
    "plugins": {
      "ip-restriction": {
        "whitelist": [
          "192.168.1.241"
        ]
      },
      "real-ip": {
        "source": "arg_realip"
      }
    },
    "upstream": {
      "type": "roundrobin",
      "nodes": {
      "httpbin.org:80": 1
      }
    }
  }'

❶ Obtain client IP address from the URL parameter realip using the built-in variables.

Send a request to the route:

curl -i "http://127.0.0.1:9080/anything?realip=192.168.1.241"

You should receive an HTTP/1.1 200 OK response.

Send another request with a different IP address:

curl -i "http://127.0.0.1:9080/anything?realip=192.168.10.24"

You should receive an HTTP/1.1 403 Forbidden response.