How to Use IP Restriction Plugin
This plugin can be very handed when you need to restrict access to your api services. Its settings are quite easy to understand. There are only two variables to control how users want to restrict access.
Users can use either config.allow
or config.deny
to allow or deny access from a single ip or ip range in CIDR notation. These two variables are arrays meaning you can add multiple ip or ip ranges to them.
Let me use some examples to demonstrate how this works.
Usage example
In the first part, I will use Admin API
to set up IP Restriction plugin
Prerequisite : A Kong instance running with Admin API
You can find official documentation here.
Let’s begin:
Create a service
1 | curl -X POST \ |
Create Route
1 | curl -X POST \ |
When we visit our route, we should get HTTP/1.1 200 OK
and result as below
1 | { |
Notice that we were accessing our service at ip 192.168.160.1
Enable plugin to deny access
You can also enable this plugin on a service or route.
1 | curl -X POST \ |
If we visit the route again, we will get HTTP/1.1 403 Forbidden
1 | { |
cURL from another IP
Create an Nginx container
1 | docker run --network=kong-ce-net --name=nginx-test -d nginx:alpine |
Get in to nginx container
1 | docker exec -it nginx-test sh |
Test curl
1 | curl http://kong-ce:8000/ip -i |
We should get HTTP/1.1 200 OK
again and this time we got
1 | { |
As we can see our IP address is 192.168.160.3
, that’s why we can access this route again.
Enable plugin to ONLY allow access
Let’s delete the previous plugin first and then apply below.
1 | curl -X POST \ |
Now the plugin only allows access from the nginx-test container.
Other deployments methods
DBless deployment
Please save below content to kong.yaml
and load it to your dbless deployment configuration.
1 | _format_version: "2.1" |
After successfully deploying your Kong instance, you should only be able to access /ip
route from nginx-test container.
Kubernetes Ingress Controller
Please change
<CLIENT_CERT_CN_NAME>
of your consumer object and put your CA root crtificate in x509 format.
Below example will deploy :
- Echo deployment
- Echo Service
- IP restriction plugin
- Ingress rule to use
IP Restriction
plugin
Please save below to ip.yaml
and use kubectl apply -f ip.yaml
to apply it.
1 | apiVersion: apps/v1 |
Extended information
There is one settings users need to know about is how to get the correct client_ip when you are running Kong behind a proxy or load balancer. For more information about getting client ip behind proxy, please refer to this serverfault answer.
When Kong is behind the proxy or LB, it sees the traffic from IP_address of the proxy or LB instead of the correct client ip. To solve this issue, there are 3 kong variables you need to use.
- TRUSTED_IPS=proxy_ip, load_balancer_ip
- REAL_IP_HEADER=X-Forwarded-For
- REAL_IP_RECURSIVE=on
After enabling these 3 variables, Kong will get the correct client ip again.