# Forward Auth

`forward-auth` 插件支持与外部授权服务集成，进行认证和授权。授权失败时，插件会将授权服务返回的状态码和响应正文发送给客户端；授权成功时，原始请求继续发往上游服务。

## 授权请求头[​](#授权请求头 "授权请求头的直接链接")

授权请求（而不是上游请求）包含以下由 APISIX 添加的请求头。这些请求头的值描述网关收到的原始客户端请求：

* `X-Forwarded-Proto`: 协议
* `X-Forwarded-Method`: HTTP 方法
* `X-Forwarded-Host`: 主机
* `X-Forwarded-Uri`: URI
* `X-Forwarded-For`: 源 IP

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

以下示例演示了如何在不同场景下使用 `forward-auth`。

要跟随前两个示例，请先设置好你的外部授权服务，或者使用 [serverless function 插件](https://docs.apiseven.com/hub/serverless-functions.md) 创建一个模拟认证服务，如下所示：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

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

  -d '{

    "id": "auth-mock",

    "uri": "/auth",

    "plugins": {

      "serverless-pre-function": {

        "phase": "rewrite",

        "functions": [

          "return function (conf, ctx)

            local core = require(\"apisix.core\");

            local authorization = core.request.header(ctx, \"Authorization\");

            if authorization == \"123\" then

              core.response.exit(200);

            elseif authorization == \"321\" then

              core.response.set_header(\"X-User-ID\", \"i-am-user\");

              core.response.exit(200);

            else core.response.set_header(\"X-Forward-Auth\", \"Fail\");

              core.response.exit(403);

            end

          end"

        ]

      }

    }

  }'
```

❶ 如果 `Authorization` 头的值为 `123`，响应 `200 OK`；

❷ 如果 `Authorization` 头的值为 `321`，设置头 `X-User-ID: i-am-user` 并响应 `200 OK`；

❸ 否则，设置头 `X-Forward-Auth: Fail` 并响应 `403 Forbidden`。

adc-auth-mock.yaml

```
services:

  - name: auth-mock-service

    routes:

      - name: auth-mock-route

        uris:

          - /auth

        plugins:

          serverless-pre-function:

            phase: rewrite

            functions:

              - |

                return function(conf, ctx)

                  local core = require("apisix.core")

                  local authorization = core.request.header(ctx, "Authorization")

                  if authorization == "123" then

                    core.response.exit(200)

                  elseif authorization == "321" then

                    core.response.set_header("X-User-ID", "i-am-user")

                    core.response.exit(200)

                  else

                    core.response.set_header("X-Forward-Auth", "Fail")

                    core.response.exit(403)

                  end

                end

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ 如果 `Authorization` 头的值为 `123`，响应 `200 OK`；

❷ 如果 `Authorization` 头的值为 `321`，设置头 `X-User-ID: i-am-user` 并响应 `200 OK`；

❸ 否则，设置头 `X-Forward-Auth: Fail` 并响应 `403 Forbidden`。

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

```
adc diff -f adc-auth-mock.yaml \

  --include-resource-type service \

  --label-selector docs-example=forward-auth-mock
```

将配置同步到网关：

```
adc sync -f adc-auth-mock.yaml \

  --include-resource-type service \

  --label-selector docs-example=forward-auth-mock
```

* Gateway API
* APISIX CRD

forward-auth-mock-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: auth-mock-plugin-config

spec:

  plugins:

    - name: serverless-pre-function

      config:

        phase: rewrite

        functions:

          - |

            return function(conf, ctx)

              local core = require("apisix.core")

              local authorization = core.request.header(ctx, "Authorization")

              if authorization == "123" then

                core.response.exit(200)

              elseif authorization == "321" then

                core.response.set_header("X-User-ID", "i-am-user")

                core.response.exit(200)

              else

                core.response.set_header("X-Forward-Auth", "Fail")

                core.response.exit(403)

              end

            end

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: auth-mock-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /auth

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: auth-mock-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

❶ 如果 `Authorization` 头的值为 `123`，响应 `200 OK`；

❷ 如果 `Authorization` 头的值为 `321`，设置头 `X-User-ID: i-am-user` 并响应 `200 OK`；

❸ 否则，设置头 `X-Forward-Auth: Fail` 并响应 `403 Forbidden`。

将配置应用到集群：

```
kubectl apply -f forward-auth-mock-ic.yaml
```

forward-auth-mock-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: auth-mock-route

spec:

  ingressClassName: apisix

  http:

    - name: auth-mock-route

      match:

        paths:

          - /auth

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: serverless-pre-function

        enable: true

        config:

          phase: rewrite

          functions:

            - |

              return function(conf, ctx)

                local core = require("apisix.core")

                local authorization = core.request.header(ctx, "Authorization")

                if authorization == "123" then

                  core.response.exit(200)

                elseif authorization == "321" then

                  core.response.set_header("X-User-ID", "i-am-user")

                  core.response.exit(200)

                else

                  core.response.set_header("X-Forward-Auth", "Fail")

                  core.response.exit(403)

                end

              end
```

❶ 如果 `Authorization` 头的值为 `123`，响应 `200 OK`；

❷ 如果 `Authorization` 头的值为 `321`，设置头 `X-User-ID: i-am-user` 并响应 `200 OK`；

❸ 否则，设置头 `X-Forward-Auth: Fail` 并响应 `403 Forbidden`。

将配置应用到集群：

```
kubectl apply -f forward-auth-mock-ic.yaml
```

### 转发指定头到上游资源[​](#转发指定头到上游资源 "转发指定头到上游资源的直接链接")

以下示例演示了如何在路由上设置 `forward-auth`，根据请求头中的值控制客户端对上游资源的访问。它还允许将授权服务中的特定头传递到上游资源。

创建一个启用了 `forward-auth` 插件的路由：

* 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": "forward-auth-route",

    "uri": "/headers",

    "plugins": {

      "forward-auth": {

        "uri": "http://127.0.0.1:9080/auth",

        "request_headers": ["Authorization"],

        "upstream_headers": ["X-User-ID"]

      }

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      },

      "type": "roundrobin"

    }

  }'
```

❶ 授权服务的 URI。

❷ 应转发到授权服务的请求头。

❸ 授权成功时，将授权服务设置的请求头转发给上游资源。

adc.yaml

```
services:

  - name: forward-auth-service

    routes:

      - name: forward-auth-route

        uris:

          - /headers

        plugins:

          forward-auth:

            uri: http://127.0.0.1:9080/auth

            request_headers:

              - Authorization

            upstream_headers:

              - X-User-ID

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ 授权服务的 URI。

❷ 应转发到授权服务的请求头。

❸ 授权成功时，将授权服务设置的请求头转发给上游资源。

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

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=forward-auth
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=forward-auth
```

* Gateway API
* APISIX CRD

forward-auth-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: forward-auth-plugin-config

spec:

  plugins:

    - name: forward-auth

      config:

        uri: http://apisix-gateway.aic.svc.cluster.local/auth

        request_headers:

          - Authorization

        upstream_headers:

          - X-User-ID

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: forward-auth-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /headers

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: forward-auth-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

❶ 授权服务的 URI。使用 Ingress Controller 时，请通过 Kubernetes 服务地址引用模拟授权服务。

❷ 应转发到授权服务的请求头。

❸ 授权成功时，将授权服务设置的请求头转发给上游资源。

将配置应用到集群：

```
kubectl apply -f forward-auth-ic.yaml
```

forward-auth-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: forward-auth-route

spec:

  ingressClassName: apisix

  http:

    - name: forward-auth-route

      match:

        paths:

          - /headers

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: forward-auth

        enable: true

        config:

          uri: http://apisix-gateway.aic.svc.cluster.local/auth

          request_headers:

            - Authorization

          upstream_headers:

            - X-User-ID
```

❶ 授权服务的 URI。使用 Ingress Controller 时，请通过 Kubernetes 服务地址引用模拟授权服务。

❷ 应转发到授权服务的请求头。

❸ 授权成功时，将授权服务设置的请求头转发给上游资源。

将配置应用到集群：

```
kubectl apply -f forward-auth-ic.yaml
```

向路由发送带有授权详情的请求：

```
curl "http://127.0.0.1:9080/headers" -H 'Authorization: 123'
```

你应该会看到如下的 `HTTP/1.1 200 OK` 响应：

```
{

  "headers": {

    "Accept": "*/*", 

    "Authorization": "123", 

    ...

  }

}
```

要验证授权服务设置的 `X-User-ID` 头是否转发到了上游服务，请发送带有相应授权详情的请求：

```
curl "http://127.0.0.1:9080/headers" -H 'Authorization: 321'
```

你应该会看到如下的 `HTTP/1.1 200 OK` 响应，显示该头已转发到上游：

```
{

  "headers": {

    "Accept": "*/*", 

    "Authorization": "123",

    "X-User-ID": "i-am-user",

    ...

  }

}
```

### 认证失败时返回指定头给客户端[​](#认证失败时返回指定头给客户端 "认证失败时返回指定头给客户端的直接链接")

以下示例演示了如何在路由上配置 `forward-auth` 以控制客户端对上游资源的访问。当认证失败时，它还会将授权服务返回的特定头传递给客户端。

创建一个启用了 `forward-auth` 插件的路由：

* 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": "forward-auth-route",

    "uri": "/headers",

    "plugins": {

      "forward-auth": {

        "uri": "http://127.0.0.1:9080/auth",

        "request_headers": ["Authorization"],

        "client_headers": ["X-Forward-Auth"]

      }

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      },

      "type": "roundrobin"

    }

  }'
```

❶ 当认证失败时，将来自授权服务的 `X-Forward-Auth` 头传回给客户端。

adc.yaml

```
services:

  - name: forward-auth-service

    routes:

      - name: forward-auth-route

        uris:

          - /headers

        plugins:

          forward-auth:

            uri: http://127.0.0.1:9080/auth

            request_headers:

              - Authorization

            client_headers:

              - X-Forward-Auth

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ 当认证失败时，将来自授权服务的 `X-Forward-Auth` 头传回给客户端。

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

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=forward-auth
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=forward-auth
```

* Gateway API
* APISIX CRD

forward-auth-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: forward-auth-plugin-config

spec:

  plugins:

    - name: forward-auth

      config:

        uri: http://apisix-gateway.aic.svc.cluster.local/auth

        request_headers:

          - Authorization

        client_headers:

          - X-Forward-Auth

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: forward-auth-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /headers

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: forward-auth-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

❶ 当认证失败时，将来自授权服务的 `X-Forward-Auth` 头传回给客户端。

将配置应用到集群：

```
kubectl apply -f forward-auth-ic.yaml
```

forward-auth-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: forward-auth-route

spec:

  ingressClassName: apisix

  http:

    - name: forward-auth-route

      match:

        paths:

          - /headers

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: forward-auth

        enable: true

        config:

          uri: http://apisix-gateway.aic.svc.cluster.local/auth

          request_headers:

            - Authorization

          client_headers:

            - X-Forward-Auth
```

❶ 当认证失败时，将来自授权服务的 `X-Forward-Auth` 头传回给客户端。

将配置应用到集群：

```
kubectl apply -f forward-auth-ic.yaml
```

发送一个不带任何认证信息的请求：

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

你应该收到一个 `HTTP/1.1 403 Forbidden` 响应：

```
...

X-Forward-Auth: Fail

Server: APISIX/3.x.x



<html>

<head><title>403 Forbidden</title></head>

<body>

<center><h1>403 Forbidden</h1></center>

<hr><center>openresty</center>

<p><em>Powered by <a href="https://apisix.apache.org/">APISIX</a>.</em></p></body>

</html>
```

### 基于 POST Body 进行授权[​](#基于-post-body-进行授权 "基于 POST Body 进行授权的直接链接")

此示例演示了如何配置 `forward-auth` 插件以根据 POST Body 数据控制访问，将值作为头传递给授权服务，并在根据 Body 数据授权失败时拒绝请求。

此示例使用内置变量 `$post_arg.*` 读取请求体参数。APISIX 会从 `application/x-www-form-urlencoded`、`application/json` 和 `multipart/form-data` 请求体中解析 `$post_arg.*`，因此客户端必须根据实际发送的请求体设置正确的 `Content-Type` 请求头。详情请参阅[内置变量](https://docs.apiseven.com/apisix/reference/built-in-variables.md)。

请先设置好你的外部授权服务，或者使用 [serverless function 插件](https://docs.apiseven.com/hub/serverless-functions.md) 创建一个模拟认证服务。该函数检查 `tenant_id` 头是否为 `123`，如果是则返回 `200 OK`，否则返回带有错误消息的 403 响应。

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

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

  -d '{

    "id": "auth-mock",

    "uri": "/auth",

    "plugins": {

      "serverless-pre-function": {

        "phase": "rewrite",

        "functions": [

          "return function(conf, ctx)

            local core = require(\"apisix.core\")

            local tenant_id = core.request.header(ctx, \"tenant_id\")

            if tenant_id == \"123\" then

              core.response.exit(200);

          else

            core.response.exit(403, \"tenant_id is \"..tenant_id .. \" but expecting 123\");

          end

        end"

        ]

      }

    }

  }'
```

adc-auth-mock.yaml

```
services:

  - name: auth-mock-service

    routes:

      - name: auth-mock-route

        uris:

          - /auth

        plugins:

          serverless-pre-function:

            phase: rewrite

            functions:

              - |

                return function(conf, ctx)

                  local core = require("apisix.core")

                  local tenant_id = core.request.header(ctx, "tenant_id")

                  if tenant_id == "123" then

                    core.response.exit(200)

                  else

                    core.response.exit(403, "tenant_id is " .. tenant_id .. " but expecting 123")

                  end

                end

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

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

```
adc diff -f adc-auth-mock.yaml \

  --include-resource-type service \

  --label-selector docs-example=forward-auth-mock
```

将配置同步到网关：

```
adc sync -f adc-auth-mock.yaml \

  --include-resource-type service \

  --label-selector docs-example=forward-auth-mock
```

* Gateway API
* APISIX CRD

forward-auth-post-mock-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: auth-mock-plugin-config

spec:

  plugins:

    - name: serverless-pre-function

      config:

        phase: rewrite

        functions:

          - |

            return function(conf, ctx)

              local core = require("apisix.core")

              local tenant_id = core.request.header(ctx, "tenant_id")

              if tenant_id == "123" then

                core.response.exit(200)

              else

                core.response.exit(403, "tenant_id is " .. tenant_id .. " but expecting 123")

              end

            end

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: auth-mock-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /auth

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: auth-mock-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将配置应用到集群：

```
kubectl apply -f forward-auth-post-mock-ic.yaml
```

forward-auth-post-mock-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: auth-mock-route

spec:

  ingressClassName: apisix

  http:

    - name: auth-mock-route

      match:

        paths:

          - /auth

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: serverless-pre-function

        enable: true

        config:

          phase: rewrite

          functions:

            - |

              return function(conf, ctx)

                local core = require("apisix.core")

                local tenant_id = core.request.header(ctx, "tenant_id")

                if tenant_id == "123" then

                  core.response.exit(200)

                else

                  core.response.exit(403, "tenant_id is " .. tenant_id .. " but expecting 123")

                end

              end
```

将配置应用到集群：

```
kubectl apply -f forward-auth-post-mock-ic.yaml
```

创建一个启用了 `forward-auth` 插件的路由：

* 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": "forward-auth-route",

    "uri": "/post",

    "methods": ["POST"],

    "plugins": {

      "forward-auth": {

        "uri": "http://127.0.0.1:9080/auth",

        "request_method": "GET",

        "extra_headers": {"tenant_id": "$post_arg.tenant_id"}

      }

    },

    "upstream": {

      "nodes": {

        "httpbin.org:80": 1

      },

      "type": "roundrobin"

    }

  }'
```

❶ 使用 POST 参数 `tenant_id` 的值设置额外的头 `tenant_id`。

adc.yaml

```
services:

  - name: forward-auth-service

    routes:

      - name: forward-auth-route

        uris:

          - /post

        methods:

          - POST

        plugins:

          forward-auth:

            uri: http://127.0.0.1:9080/auth

            request_method: GET

            extra_headers:

              tenant_id: "$post_arg.tenant_id"

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ 使用 POST 参数 `tenant_id` 的值设置额外的头 `tenant_id`。

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

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=forward-auth
```

将配置同步到网关：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=forward-auth
```

* Gateway API
* APISIX CRD

forward-auth-post-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: forward-auth-post-plugin-config

spec:

  plugins:

    - name: forward-auth

      config:

        uri: http://apisix-gateway.aic.svc.cluster.local/auth

        request_method: GET

        extra_headers:

          tenant_id: "$post_arg.tenant_id"

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: forward-auth-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /post

          method: POST

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: forward-auth-post-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

❶ 使用 POST 参数 `tenant_id` 的值设置额外的头 `tenant_id`。

将配置应用到集群：

```
kubectl apply -f forward-auth-post-ic.yaml
```

forward-auth-post-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: forward-auth-route

spec:

  ingressClassName: apisix

  http:

    - name: forward-auth-route

      match:

        paths:

          - /post

        methods:

          - POST

      upstreams:

      - name: httpbin-external-domain

      plugins:

      - name: forward-auth

        enable: true

        config:

          uri: http://apisix-gateway.aic.svc.cluster.local/auth

          request_method: GET

          extra_headers:

            tenant_id: "$post_arg.tenant_id"
```

❶ 使用 POST 参数 `tenant_id` 的值设置额外的头 `tenant_id`。

将配置应用到集群：

```
kubectl apply -f forward-auth-post-ic.yaml
```

发送一个在 JSON 请求体中包含 `tenant_id` 的 POST 请求：

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

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

  -d '{"tenant_id": "123"}'
```

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

发送一个包含不同 `tenant_id` 的 POST 请求：

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

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

  -d '{"tenant_id": "000"}'
```

你应该收到如下的 `HTTP/1.1 403 Forbidden` 响应：

```
tenant_id is 000 but expecting 123
```

## 排查授权延迟和连接复用问题[​](#排查授�权延迟和连接复用问题 "排查授权延迟和连接复用问题的直接链接")

分别测量授权服务和应用上游的性能。比较结果前，请记录网关镜像、工作进程数、`forward-auth` 配置、选用的 HTTP 客户端、授权请求的目标地址和请求速率。客户端的可用性和行为因版本而异，请参阅[配置参考](https://docs.apiseven.com/hub/forward-auth/configuration.md)。

* 在负载稳定时，检查授权响应延迟、错误、新建的 TCP 连接和 TLS 握手。对比空闲连接过期后进行的短时测试与能够复用连接的持续测试。
* 除了观察实例总量，还要观察各个工作进程或其连接。一个工作进程连接池中的连接无法供另一个工作进程使用。将套接字数量与 `keepalive_pool` 对照时，区分活跃连接和保留的空闲连接。
* 对采用每个工作进程独立空闲连接池的客户端，可按实例数 × 工作进程数 × 独立连接池数 × 连接池大小估算可保留的空闲连接数。这个数值并非活跃请求的上限。不同的目标地址或连接设置可能产生独立的连接池，授权服务器也可能提前关闭空闲连接。
* 调整连接池大小前，请确认已启用 keepalive，且连接两端均允许复用。将连接池大小设为 `256` 不会启用 keepalive，也无法证明 `256` 适合当前负载。
* 每次只更改一项配置，并对比变更前后的请求延迟和授权服务连接数。检查工作进程的 CPU 使用情况以及授权服务的饱和程度，避免更大的空闲连接池掩盖实际瓶颈。

使用请求 ID 和耗时数据关联记录，避免记录授权凭据。连接复用和较新的 HTTP 客户端都不会缓存授权判定，符合条件的请求仍会调用授权服务。
