# Request Validation

`request-validation` 插件在将请求转发到上游服务之前对其进行验证。该插件使用 [JSON Schema](https://github.com/api7/jsonschema) 进行验证，并且可以验证请求的请求头（headers）和请求体（body）。

请参阅 [JSON schema 规范](https://json-schema.org/specification) 以了解有关语法的更多信息。

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

以下示例展示了如何在不同场景下配置 `request-validation`。

### 验证请求头[​](#验证请求头 "验证请求头的直接链接")

以下示例展示了如何根据定义的 JSON schema 验证请求头。

如下所示创建带有 `request-validation` 插件的路由：

* 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": "request-validation-route",

    "uri": "/get",

    "plugins": {

      "request-validation": {

        "header_schema": {

          "type": "object",

          "required": ["User-Agent", "Host"],

          "properties": {

            "User-Agent": {

              "type": "string",

              "pattern": "^curl\/"

            },

            "Host": {

              "type": "string",

              "enum": ["httpbin.org", "httpbin"]

            }

          }

        }

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

adc.yaml

```
services:

  - name: request-validation-service

    routes:

      - name: request-validation-route

        uris:

          - /get

        plugins:

          request-validation:

            header_schema:

              type: object

              required:

                - User-Agent

                - Host

              properties:

                User-Agent:

                  type: string

                  pattern: "^curl/"

                Host:

                  type: string

                  enum:

                    - httpbin.org

                    - httpbin

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

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

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=request-validation
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=request-validation
```

* Gateway API
* APISIX CRD

request-validation-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: request-validation-plugin-config

spec:

  plugins:

    - name: request-validation

      config:

        header_schema:

          type: object

          required:

            - User-Agent

            - Host

          properties:

            User-Agent:

              type: string

              pattern: "^curl/"

            Host:

              type: string

              enum:

                - httpbin.org

                - httpbin

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: request-validation-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /get

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: request-validation-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

request-validation-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: request-validation-route

spec:

  ingressClassName: apisix

  http:

    - name: request-validation-route

      match:

        paths:

          - /get

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: request-validation

        enable: true

        config:

          header_schema:

            type: object

            required:

              - User-Agent

              - Host

            properties:

              User-Agent:

                type: string

                pattern: "^curl/"

              Host:

                type: string

                enum:

                  - httpbin.org

                  - httpbin
```

将配置应用到集群：

```
kubectl apply -f request-validation-ic.yaml
```

❶ `required`：要求请求必须包含指定的请求头。

❷ `properties`：要求请求头必须符合指定的条件。

#### 验证符合 Schema 的请求[​](#验证符合-schema-的请求 "验证符合 Schema 的请求的直接链接")

发送一个带有符合 Schema 的 `Host: httpbin` 请求头的请求：

```
curl -i "http://127.0.0.1:9080/get" -H "Host: httpbin"
```

你应该收到类似于以下的 `HTTP/1.1 200 OK` 响应：

```
{

  "args": {}, 

  "headers": {

    "Accept": "*/*", 

    "Host": "httpbin", 

    "User-Agent": "curl/7.74.0", 

    "X-Amzn-Trace-Id": "Root=1-6509ae35-63d1e0fd3934e3f221a95dd8", 

    "X-Forwarded-Host": "httpbin"

  }, 

  "origin": "127.0.0.1, 183.17.233.107", 

  "url": "http://httpbin/get"

}
```

#### 验证不符合 Schema 的请求[​](#验证不符合-schema-的请求 "验证不符合 Schema 的请求的直接链接")

发送一个不带任何请求头的请求：

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

你应该收到 `HTTP/1.1 400 Bad Request` 响应，表明请求验证失败：

```
property "Host" validation failed: matches none of the enum value
```

发送一个包含必需请求头但不符合其值要求的请求：

```
curl -i "http://127.0.0.1:9080/get" -H "Host: httpbin" -H "User-Agent: cli-mock"
```

你应该收到 `HTTP/1.1 400 Bad Request` 响应，表明 `User-Agent` 请求头的值不匹配预期模式：

```
property "User-Agent" validation failed: failed to match pattern "^curl/" with "cli-mock"
```

### 自定义拒绝消息和状态码[​](#自定义拒绝消息和状态码 "自定义拒绝消息和状态码的直接链接")

以下示例展示了当验证失败时如何自定义响应状态码和消息。

如下所示配置带有 `request-validation` 插件的路由：

* 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": "request-validation-route",

    "uri": "/get",

    "plugins": {

      "request-validation": {

        "header_schema": {

          "type": "object",

          "required": ["Host"],

          "properties": {

            "Host": {

              "type": "string",

              "enum": ["httpbin.org", "httpbin"]

            }

          }

        },

        "rejected_code": 403,

        "rejected_msg": "Request header validation failed."

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

adc.yaml

```
services:

  - name: request-validation-service

    routes:

      - name: request-validation-route

        uris:

          - /get

        plugins:

          request-validation:

            header_schema:

              type: object

              required:

                - Host

              properties:

                Host:

                  type: string

                  enum:

                    - httpbin.org

                    - httpbin

            rejected_code: 403

            rejected_msg: "Request header validation failed."

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

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

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=request-validation
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=request-validation
```

* Gateway API
* APISIX CRD

request-validation-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: request-validation-plugin-config

spec:

  plugins:

    - name: request-validation

      config:

        header_schema:

          type: object

          required:

            - Host

          properties:

            Host:

              type: string

              enum:

                - httpbin.org

                - httpbin

        rejected_code: 403

        rejected_msg: "Request header validation failed."

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: request-validation-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /get

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: request-validation-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

request-validation-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: request-validation-route

spec:

  ingressClassName: apisix

  http:

    - name: request-validation-route

      match:

        paths:

          - /get

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: request-validation

        enable: true

        config:

          header_schema:

            type: object

            required:

              - Host

            properties:

              Host:

                type: string

                enum:

                  - httpbin.org

                  - httpbin

          rejected_code: 403

          rejected_msg: "Request header validation failed."
```

将配置应用到集群：

```
kubectl apply -f request-validation-ic.yaml
```

❶ `rejected_code`：自定义拒绝状态码。

❷ `rejected_msg`：自定义拒绝消息。

发送一个带有配置错误的 `Host` 请求头的请求：

```
curl -i "http://127.0.0.1:9080/get" -H "Host: httpbin2"
```

你应该收到 `HTTP/1.1 403 Forbidden` 响应和自定义消息：

```
Request header validation failed.
```

### 验证请求体[​](#验证请求体 "验证请求体的直接链接")

以下示例展示了如何根据定义的 JSON schema 验证请求体。

`request-validation` 插件支持验证两种类型的媒体类型：

* `application/json`
* `application/x-www-form-urlencoded`

#### 验证 JSON 请求体[​](#验证-json-请求体 "验证 JSON 请求体的直接链接")

如下所示创建带有 `request-validation` 插件的路由：

* 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": "request-validation-route",

    "uri": "/post",

    "plugins": {

      "request-validation": {

        "header_schema": {

          "type": "object",

          "required": ["Content-Type"],

          "properties": {

            "Content-Type": {

            "type": "string",

            "pattern": "^application\/json$"

            }

          }

        },

        "body_schema": {

          "type": "object",

          "required": ["required_payload"],

          "properties": {

            "required_payload": {"type": "string"},

            "boolean_payload": {"type": "boolean"},

            "array_payload": {

              "type": "array",

              "minItems": 1,

              "items": {

                "type": "integer",

                "minimum": 200,

                "maximum": 599

              },

              "uniqueItems": true,

              "default": [200]

            }

          }

        }

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

adc.yaml

```
services:

  - name: request-validation-service

    routes:

      - name: request-validation-route

        uris:

          - /post

        plugins:

          request-validation:

            header_schema:

              type: object

              required:

                - Content-Type

              properties:

                Content-Type:

                  type: string

                  pattern: "^application/json$"

            body_schema:

              type: object

              required:

                - required_payload

              properties:

                required_payload:

                  type: string

                boolean_payload:

                  type: boolean

                array_payload:

                  type: array

                  minItems: 1

                  items:

                    type: integer

                    minimum: 200

                    maximum: 599

                  uniqueItems: true

                  default:

                    - 200

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

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

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=request-validation
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=request-validation
```

* Gateway API
* APISIX CRD

request-validation-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: request-validation-plugin-config

spec:

  plugins:

    - name: request-validation

      config:

        header_schema:

          type: object

          required:

            - Content-Type

          properties:

            Content-Type:

              type: string

              pattern: "^application/json$"

        body_schema:

          type: object

          required:

            - required_payload

          properties:

            required_payload:

              type: string

            boolean_payload:

              type: boolean

            array_payload:

              type: array

              minItems: 1

              items:

                type: integer

                minimum: 200

                maximum: 599

              uniqueItems: true

              default:

                - 200

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: request-validation-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /post

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: request-validation-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

request-validation-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: request-validation-route

spec:

  ingressClassName: apisix

  http:

    - name: request-validation-route

      match:

        paths:

          - /post

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: request-validation

        enable: true

        config:

          header_schema:

            type: object

            required:

              - Content-Type

            properties:

              Content-Type:

                type: string

                pattern: "^application/json$"

          body_schema:

            type: object

            required:

              - required_payload

            properties:

              required_payload:

                type: string

              boolean_payload:

                type: boolean

              array_payload:

                type: array

                minItems: 1

                items:

                  type: integer

                  minimum: 200

                  maximum: 599

                uniqueItems: true

                default:

                  - 200
```

将配置应用到集群：

```
kubectl apply -f request-validation-ic.yaml
```

发送一个符合 Schema 的 JSON 请求体的请求进行验证：

```
curl -i "http://127.0.0.1:9080/post" -X POST \

  -H "Content-Type: application/json" \

  -d '{"required_payload":"hello", "array_payload":[301]}'
```

你应该收到类似于以下的 `HTTP/1.1 200 OK` 响应：

```
{

  "args": {}, 

  "data": "{\"array_payload\":[301],\"required_payload\":\"hello\"}", 

  "files": {}, 

  "form": {}, 

  "headers": {

    ...

  }, 

  "json": {

    "array_payload": [

      301

    ],

    "required_payload": "hello"

  },

  "origin": "127.0.0.1, 183.17.233.107", 

  "url": "http://127.0.0.1/post"

}
```

如果你发送一个未指定 `Content-Type: application/json` 的请求：

```
curl -i "http://127.0.0.1:9080/post" -X POST \

  -d '{"required_payload":"hello,world"}'
```

你应该收到类似于以下的 `HTTP/1.1 400 Bad Request` 响应：

```
property "Content-Type" validation failed: failed to match pattern "^application/json$" with "application/x-www-form-urlencoded"
```

同样，如果你发送一个缺少必需 JSON 字段 `required_payload` 的请求：

```
curl -i "http://127.0.0.1:9080/post" -X POST \

  -H "Content-Type: application/json" \

  -d '{}'
```

你应该收到 `HTTP/1.1 400 Bad Request` 响应：

```
property "required_payload" is required
```

#### 验证 URL 编码表单请求体[​](#验证-url-编码表单请求体 "验证 URL 编码表单请求体的直接链接")

如下所示创建带有 `request-validation` 插件的路由：

* 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": "request-validation-route",

    "uri": "/post",

    "plugins": {

      "request-validation": {

        "header_schema": {

          "type": "object",

          "required": ["Content-Type"],

          "properties": {

            "Content-Type": {

              "type": "string",

              "pattern": "^application\/x-www-form-urlencoded$"

            }

          }

        },

        "body_schema": {

          "type": "object",

          "required": ["required_payload","enum_payload"],

          "properties": {

            "required_payload": {"type": "string"},

            "enum_payload": {

              "type": "string",

              "enum": ["enum_string_1", "enum_string_2"],

              "default": "enum_string_1"

            }

          }

        }

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

adc.yaml

```
services:

  - name: request-validation-service

    routes:

      - name: request-validation-route

        uris:

          - /post

        plugins:

          request-validation:

            header_schema:

              type: object

              required:

                - Content-Type

              properties:

                Content-Type:

                  type: string

                  pattern: "^application/x-www-form-urlencoded$"

            body_schema:

              type: object

              required:

                - required_payload

                - enum_payload

              properties:

                required_payload:

                  type: string

                enum_payload:

                  type: string

                  enum:

                    - enum_string_1

                    - enum_string_2

                  default: enum_string_1

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

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

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=request-validation
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=request-validation
```

* Gateway API
* APISIX CRD

request-validation-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: request-validation-plugin-config

spec:

  plugins:

    - name: request-validation

      config:

        header_schema:

          type: object

          required:

            - Content-Type

          properties:

            Content-Type:

              type: string

              pattern: "^application/x-www-form-urlencoded$"

        body_schema:

          type: object

          required:

            - required_payload

            - enum_payload

          properties:

            required_payload:

              type: string

            enum_payload:

              type: string

              enum:

                - enum_string_1

                - enum_string_2

              default: enum_string_1

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: request-validation-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /post

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: request-validation-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

request-validation-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: request-validation-route

spec:

  ingressClassName: apisix

  http:

    - name: request-validation-route

      match:

        paths:

          - /post

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: request-validation

        enable: true

        config:

          header_schema:

            type: object

            required:

              - Content-Type

            properties:

              Content-Type:

                type: string

                pattern: "^application/x-www-form-urlencoded$"

          body_schema:

            type: object

            required:

              - required_payload

              - enum_payload

            properties:

              required_payload:

                type: string

              enum_payload:

                type: string

                enum:

                  - enum_string_1

                  - enum_string_2

                default: enum_string_1
```

将配置应用到集群：

```
kubectl apply -f request-validation-ic.yaml
```

发送一个带有 URL 编码表单数据的请求进行验证：

```
curl -i "http://127.0.0.1:9080/post" -X POST \

  -H "Content-Type: application/x-www-form-urlencoded" \

  -d "required_payload=hello&enum_payload=enum_string_1"
```

你应该收到类似于以下的 `HTTP/1.1 200 OK` 响应：

```
{

  "args": {}, 

  "data": "", 

  "files": {}, 

  "form": {

    "enum_payload": "enum_string_1", 

    "required_payload": "hello"

  }, 

  "headers": {

    ...

  }, 

  "json": null, 

  "origin": "127.0.0.1, 183.17.233.107", 

  "url": "http://127.0.0.1/post"

}
```

发送一个缺少 URL 编码字段 `enum_payload` 的请求：

```
curl -i "http://127.0.0.1:9080/post" -X POST \

  -H "Content-Type: application/x-www-form-urlencoded" \

  -d "required_payload=hello"
```

你应该收到以下的 `HTTP/1.1 400 Bad Request` 响应：

```
property "enum_payload" is required
```

## 附录：JSON Schema[​](#附录json-schema "附录：JSON Schema的直接链接")

以下部分提供了样板 JSON schema，你可以根据需要进行调整、组合并在此插件中使用。有关完整参考，请参阅 [JSON schema 规范](https://json-schema.org/specification)。

### 枚举值[​](#枚举值 "枚举值的直接链接")

```
{

  "body_schema": {

    "type": "object",

    "required": ["enum_payload"],

    "properties": {

      "enum_payload": {

        "type": "string",

        "enum": ["enum_string_1", "enum_string_2"],

        "default": "enum_string_1"

      }

    }

  }

}
```

### 布尔值[​](#布尔值 "布尔值的直接链接")

```
{

  "body_schema": {

    "type": "object",

    "required": ["bool_payload"],

    "properties": {

      "bool_payload": {

        "type": "boolean",

        "default": true

      }

    }

  }

}
```

### 数值[​](#数值 "数值的直接链接")

```
{

  "body_schema": {

    "type": "object",

    "required": ["integer_payload"],

    "properties": {

      "integer_payload": {

        "type": "integer",

        "minimum": 1,

        "maximum": 65535

      }

    }

  }

}
```

### 字符串[​](#字符串 "字符串的直接链接")

```
{

  "body_schema": {

    "type": "object",

    "required": ["string_payload"],

    "properties": {

      "string_payload": {

        "type": "string",

        "minLength": 1,

        "maxLength": 32

      }

    }

  }

}
```

### 字符串正则表达式[​](#字符串正则表达式 "字符串正则表达式的直接链接")

```
{

  "body_schema": {

    "type": "object",

    "required": ["regex_payload"],

    "properties": {

      "regex_payload": {

        "type": "string",

        "minLength": 1,

        "maxLength": 32,

        "pattern": "[[^[a-zA-Z0-9_]+$]]"

      }

    }

  }

}
```

### 数组[​](#数组 "数组的直接链接")

```
{

  "body_schema": {

    "type": "object",

    "required": ["array_payload"],

    "properties": {

      "array_payload": {

        "type": "array",

        "minItems": 1,

        "items": {

          "type": "integer",

          "minimum": 200,

          "maximum": 599

        },

        "uniqueItems": true,

        "default": [200, 302]

      }

    }

  }

}
```
