# IP Restriction

`ip-restriction` 插件支持通过配置 IP 地址白名单或黑名单来限制对上游资源的访问。限制对资源的 IP 访问有助于防止未经授权的访问并加强 API 安全性。

## 示例[​](#示例 "��示例的直接链接")

下面的示例展示了如何在不同场景下配置 `ip-restriction` 插件。

### 通过白名单限制访问[​](#通过白名单限制访问 "通过白名单限制访问的直接链接")

以下示例展示了如何将允许访问上游资源的 IP 地址列入白名单，并自定义拒绝访问时的错误消息。

* Admin API
* ADC
* Ingress Controller

创建一个启用了 `ip-restriction` 插件的路由：

```
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

      }

    }

  }'
```

adc.yaml

```
services:

  - name: ip-restriction-service

    routes:

      - name: ip-restriction-route

        uris:

          - /anything

        plugins:

          ip-restriction:

            whitelist:

              - "192.168.0.1/24"

            message: "Access denied"

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览变更，并确认变更仅影响本指南使用的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ip-restriction
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ip-restriction
```

使用 kubectl port-forward 时的客户端 IP

使用 `kubectl port-forward` 进行本地测试时，无论本机的实际 IP 地址是什么，APISIX 都会将 `127.0.0.1` 视为客户端 IP。采用这种方式测试时，请确保白名单或黑名单中包含 `127.0.0.1`。

NodePort 或 LoadBalancer Service 默认不会保留客户端 IP。要保留客户端 IP，请将网关 Service 的 [`externalTrafficPolicy`](https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/#preserving-the-client-source-ip) 设为 `Local`，并确保外部负载均衡器转发源 IP。此设置只会将流量路由到节点本地的网关 Pod，因此流量可能分布不均，没有本地端点的节点会丢弃请求。如果可信代理替换了源 IP，请配置 [`real-ip`](https://docs.apiseven.com/hub/real-ip.md) 插件，改为从代理提供的值中获取源 IP。

* Gateway API
* APISIX CRD

ip-restriction-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: ip-restriction-plugin-config

spec:

  plugins:

    - name: ip-restriction

      config:

        whitelist:

          - "192.168.0.1/24"

        message: "Access denied"

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: ip-restriction-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: ip-restriction-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f ip-restriction-ic.yaml
```

ip-restriction-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: ip-restriction-route

spec:

  ingressClassName: apisix

  http:

    - name: ip-restriction-route

      match:

        paths:

          - /anything

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: ip-restriction

        enable: true

        config:

          whitelist:

            - "192.168.0.1/24"

          message: "Access denied"
```

将配置应用到集群：

```
kubectl apply -f ip-restriction-ic.yaml
```

❶ 替换为你想要列入白名单的 IP 地址。

❷ 自定义拒绝访问时的错误消息。

发送请求到该路由：

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

如果你的 IP 被允许，你应该收到 `HTTP/1.1 200 OK` 响应。如果不是，你应该收到 `HTTP/1.1 403 Forbidden` 响应以及以下错误消息：

```
{"message":"Access denied"}
```

### 使用修改后的 IP 限制访问[​](#使用修改后的-ip-限制访问 "使用修改后的 IP 限制访问的直接链接")

以下示例展示了如何使用 `real-ip` 插件修改用于 IP 限制的 IP。这在 APISIX 位于反向代理之后且 APISIX 无法获取真实客户端 IP 时特别有用。

* Admin API
* ADC
* Ingress Controller

创建一个路由如下：

```
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

      }

    }

  }'
```

❶ 使用 [内置变量](https://docs.apiseven.com/apisix/reference/built-in-variables.md) 从 URL 参数 `realip` 获取客户端 IP 地址。

adc.yaml

```
services:

  - name: ip-restriction-service

    routes:

      - name: ip-restriction-route

        uris:

          - /anything

        plugins:

          ip-restriction:

            whitelist:

              - "192.168.1.241"

          real-ip:

            source: arg_realip

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ 使用 [内置变量](https://docs.apiseven.com/apisix/reference/built-in-variables.md) 从 URL 参数 `realip` 获取客户端 IP 地址。

预览变更，并确认变更仅影响本指南使用的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ip-restriction
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ip-restriction
```

* Gateway API
* APISIX CRD

ip-restriction-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: ip-restriction-realip-plugin-config

spec:

  plugins:

    - name: ip-restriction

      config:

        whitelist:

          - "192.168.1.241"

    - name: real-ip

      config:

        source: arg_realip

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: ip-restriction-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: ip-restriction-realip-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

ip-restriction-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixUpstream

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  ingressClassName: apisix

  externalNodes:

  - type: Domain

    name: httpbin.org

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: ip-restriction-route

spec:

  ingressClassName: apisix

  http:

    - name: ip-restriction-route

      match:

        paths:

          - /anything

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: ip-restriction

        enable: true

        config:

          whitelist:

            - "192.168.1.241"

      - name: real-ip

        enable: true

        config:

          source: arg_realip
```

❶ 使用 [内置变量](https://docs.apiseven.com/apisix/reference/built-in-variables.md) 从 URL 参数 `realip` 获取客户端 IP 地址。

将配置应用到集群：

```
kubectl apply -f ip-restriction-ic.yaml
```

发送请求到该路由：

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

你应该收到 `HTTP/1.1 200 OK` 响应。

发送另一个使用不同 IP 地址的请求：

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

你应该收到 `HTTP/1.1 403 Forbidden` 响应。
