# OPA

`opa` 插件将 APISIX 和 API7 网关与 [Open Policy Agent（OPA）](https://www.openpolicyagent.org)集成。OPA 是用于定义和实施授权决策的策略引擎。授权逻辑使用 [Rego](https://www.openpolicyagent.org/docs/latest/policy-language/) 定义并存储在 OPA 中。

对于发送到受保护路由的每个请求，OPA 都会评估已配置的策略，并告知网关是否允许访问上游。

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

以下示例展示如何实施请求方法策略、检查发送给 OPA 的数据、返回自定义响应，以及实现基于角色的访问控制。

继续之前，请确保 OPA 服务器正在运行。你可以使用 Docker 启动一个，或将其部署到 Kubernetes：

* Docker
* Kubernetes

将 `GATEWAY_CONTAINER` 设置为正在运行的 APISIX 或 API7 网关容器。创建专用网络并将网关连接到该网络：

```
export GATEWAY_CONTAINER=replace-with-gateway-container-name



docker network create gateway-opa-net

docker network connect gateway-opa-net "$GATEWAY_CONTAINER"
```

在同一网络中启动 OPA，并仅在本地主机上公开其 API：

```
docker run -d \

  --name opa-server \

  --network gateway-opa-net \

  -p 127.0.0.1:8181:8181 \

  openpolicyagent/opa:1.20.2 \

  run --server --addr=0.0.0.0:8181 --log-level=debug
```

等待 OPA 就绪：

```
until curl --max-time 2 -fsS "http://127.0.0.1:8181/health" > /dev/null; do

  sleep 1

done
```

在集群中为 OPA 创建 `Deployment` 和 `Service`：

opa-server.yaml

```
apiVersion: apps/v1

kind: Deployment

metadata:

  namespace: aic

  name: opa

spec:

  replicas: 1

  selector:

    matchLabels:

      app: opa

  template:

    metadata:

      labels:

        app: opa

    spec:

      containers:

        - name: opa

          image: openpolicyagent/opa:1.20.2

          args:

            - run

            - --server

            - --addr=0.0.0.0:8181

            - --log-level=debug

          ports:

            - name: http

              containerPort: 8181

          livenessProbe:

            httpGet:

              path: /health

              port: http

            initialDelaySeconds: 5

            periodSeconds: 5

          readinessProbe:

            httpGet:

              path: /health

              port: http

            initialDelaySeconds: 5

            periodSeconds: 5

---

apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: opa

spec:

  selector:

    app: opa

  ports:

    - name: http

      port: 8181

      targetPort: http
```

将配置应用到集群：

```
kubectl apply -f opa-server.yaml

kubectl rollout status -n aic deployment/opa
```

等待 OPA Pod 就绪。就绪后，可以在集群内通过 `http://opa.aic.svc.cluster.local:8181` 访问 OPA 服务器。要从集群外向其推送策略，请设置端口转发：

```
kubectl port-forward -n aic svc/opa 8181:8181 &
```

### 实现基本策略[​](#implement-a-basic-policy "实现基本策略的直接链接")

以下示例在 OPA 中实现了一个基本的授权策略，仅允许 GET 请求。

创建一个仅允许 HTTP GET 请求的 OPA 策略：

```
curl "http://127.0.0.1:8181/v1/policies/getonly" -X PUT  \

  -H "Content-Type: text/plain" \

  -d '

package getonly



default allow := false



allow if {

    input.request.method == "GET"

}'
```

创建一个启用了 `opa` 插件的路由：

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

    "uri": "/anything",

    "plugins": {

      "opa": {

        "host": "http://opa-server:8181",

        "policy": "getonly"

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

❶ 配置网关可访问的 OPA 服务器地址。

❷ 将授权策略设置为 `getonly`。

adc.yaml

```
services:

  - name: opa-service

    labels:

      docs-example: opa

    routes:

      - name: opa-route

        uris:

          - /anything

        plugins:

          opa:

            host: "http://opa-server:8181"

            policy: getonly

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ 配置网关可访问的 OPA 服务器地址。

❷ 将授权策略设置为 `getonly`。

预览带有示例标签的 Service 变更：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=opa
```

同步已审核的变更：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=opa
```

* Gateway API
* APISIX CRD

opa-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: opa-plugin-config

spec:

  plugins:

    - name: opa

      config:

        host: "http://opa.aic.svc.cluster.local:8181"

        policy: getonly

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: opa-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: PathPrefix

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: opa-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

❶ 配置 OPA 服务器地址。

❷ 将授权策略设置为 `getonly`。

将配置应用到集群：

```
kubectl apply -f opa-ic.yaml
```

opa-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: opa-route

spec:

  ingressClassName: apisix

  http:

    - name: opa-route

      match:

        paths:

          - /anything

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: opa

          enable: true

          config:

            host: "http://opa.aic.svc.cluster.local:8181"

            policy: getonly
```

❶ 配置 OPA 服务器地址。

❷ 将授权策略设置为 `getonly`。

将配置应用到集群：

```
kubectl apply -f opa-ic.yaml
```

要验证该策略，向路由发送一个 GET 请求：

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

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

向路由发送另一个使用 PUT 的请求：

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

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

### 理解数据格式[​](#理解数据格式 "理解数据格式的直接链接")

APISIX 会向 OPA 发送一个 `input` 文档，其中包含请求上下文以及插件配置中启用的任何可选网关资源。本示例沿用[实现基本策略](#implement-a-basic-policy)中的策略和路由。

假设你的 OPA 服务器已使用 `--log-level debug` 启动，并且你已完成[上一个示例](#implement-a-basic-policy)中的验证步骤，向示例路由发送了请求。

检查 OPA 服务器日志。你应该会看到类似以下的条目。地址、端口、时间戳和请求元数据会因环境而异：

```
{

  "client_addr": "192.168.215.1:58467",

  "level": "info",

  "msg": "Received request.",

  "req_body": "{\"input\":{\"type\":\"http\",\"var\":{\"server_port\":\"9080\",\"timestamp\":1752400020,\"server_addr\":\"192.168.107.3\",\"remote_port\":\"58544\",\"remote_addr\":\"192.168.107.1\"},\"request\":{\"host\":\"127.0.0.1\",\"path\":\"/anything\",\"headers\":{\"host\":\"127.0.0.1:9080\",\"accept\":\"*/*\",\"user-agent\":\"curl/8.7.1\"},\"query\":{},\"port\":9080,\"scheme\":\"http\",\"method\":\"PUT\"}}}",

  "req_id": 12,

  "req_method": "POST",

  "req_params": {},

  "req_path": "/v1/data/getonly",

  "time": "2025-07-14T15:07:00Z"

}
```

其中 `req_body` 显示了 APISIX 推送的数据：

```
{

  "input": {

    "type": "http",

    "var": {

      "server_port": "9080",

      "timestamp": 1752400020,

      "server_addr": "192.168.107.3",

      "remote_port": "58544",

      "remote_addr": "192.168.107.1"

    },

    "request": {

      "host": "127.0.0.1",

      "path": "/anything",

      "headers": {

        "host": "127.0.0.1:9080",

        "accept": "*/*",

        "user-agent": "curl/8.7.1"

      },

      "query": {},

      "port": 9080,

      "scheme": "http",

      "method": "PUT"

    }

  }

}
```

现在，更新[之前创建的路由](#implement-a-basic-policy)上的插件以包含路由信息：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes/opa-route" -X PATCH \

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

  -d '{

    "plugins": {

      "opa": {

        "with_route": true

      }

    }

  }'
```

更新 `adc.yaml`，添加 `with_route: true`：

adc.yaml

```
services:

  - name: opa-service

    labels:

      docs-example: opa

    routes:

      - name: opa-route

        uris:

          - /anything

        plugins:

          opa:

            host: "http://opa-server:8181"

            policy: getonly

            with_route: true

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览带有示例标签的 Service 变更：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=opa
```

同步已审核的变更：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=opa
```

* Gateway API
* APISIX CRD

更新 `opa-ic.yaml`，添加 `with_route: true`：

opa-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: opa-plugin-config

spec:

  plugins:

    - name: opa

      config:

        host: "http://opa.aic.svc.cluster.local:8181"

        policy: getonly

        with_route: true

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: opa-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: PathPrefix

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: opa-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

将更新后的配置应用到集群：

```
kubectl apply -f opa-ic.yaml
```

更新 `opa-ic.yaml`，添加 `with_route: true`：

opa-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: opa-route

spec:

  ingressClassName: apisix

  http:

    - name: opa-route

      match:

        paths:

          - /anything

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: opa

          enable: true

          config:

            host: "http://opa.aic.svc.cluster.local:8181"

            policy: getonly

            with_route: true
```

将更新后的配置应用到集群：

```
kubectl apply -f opa-ic.yaml
```

向路由发送请求：

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

OPA 服务器日志中应该会出现一条新记录。地址、端口、时间戳和请求元数据会因环境而异：

```
{

  "client_addr": "192.168.215.1:43706",

  "level": "info",

  "msg": "Received request.",

  "req_body": "{\"input\":{\"route\":{\"id\":\"opa-route\",\"uri\":\"/anything\",\"update_time\":1752395758,\"plugins\":{\"opa\":{\"keepalive_pool\":5,\"keepalive_timeout\":60000,\"host\":\"http://opa-server:8181\",\"ssl_verify\":true,\"with_route\":true,\"with_service\":false,\"with_consumer\":false,\"timeout\":3000,\"keepalive\":true,\"policy\":\"getonly\"}},\"priority\":0,\"status\":1,\"create_time\":1752393063},\"type\":\"http\",\"var\":{\"server_port\":\"9080\",\"timestamp\":1752396233,\"server_addr\":\"192.168.107.3\",\"remote_port\":\"47838\",\"remote_addr\":\"192.168.107.1\"},\"request\":{\"host\":\"127.0.0.1\",\"path\":\"/anything\",\"headers\":{\"host\":\"127.0.0.1:9080\",\"accept\":\"*/*\",\"user-agent\":\"curl/8.7.1\"},\"query\":{},\"port\":9080,\"scheme\":\"http\",\"method\":\"GET\"}}}",

  "req_id": 14,

  "req_method": "POST",

  "req_params": {},

  "req_path": "/v1/data/getonly",

  "time": "2025-07-13T08:43:53Z"

}
```

`req_body` 现在包含了路由信息：

```
{

  "input": {

    "route": {

      "id": "opa-route",

      "uri": "/anything",

      "update_time": 1752395758,

      "plugins": {

        "opa": {

          "keepalive_pool": 5,

          "keepalive_timeout": 60000,

          "host": "http://opa-server:8181",

          "ssl_verify": true,

          "with_route": true,

          "with_service": false,

          "with_consumer": false,

          "timeout": 3000,

          "keepalive": true,

          "policy": "getonly"

        }

      },

      "priority": 0,

      "status": 1,

      "create_time": 1752393063

    },

    "type": "http",

    "var": {

      "server_port": "9080",

      "timestamp": 1752396233,

      "server_addr": "192.168.107.3",

      "remote_port": "47838",

      "remote_addr": "192.168.107.1"

    },

    "request": {

      "host": "127.0.0.1",

      "path": "/anything",

      "headers": {

        "host": "127.0.0.1:9080",

        "accept": "*/*",

        "user-agent": "curl/8.7.1"

      },

      "query": {},

      "port": 9080,

      "scheme": "http",

      "method": "GET"

    }

  }

}
```

### 返回自定义响应[​](#返回自定义响应 "返回自定义响应的直接链接")

以下示例展示当 OPA 拒绝请求时，如何返回自定义状态码、响应头和消息。

创建一个仅允许 HTTP GET 请求并在未获授权时返回 `302` 和自定义消息的 OPA 策略：

```
curl "http://127.0.0.1:8181/v1/policies/customresp" -X PUT \

  -H "Content-Type: text/plain" \

  -d '

package customresp



default allow := false



allow if {

  input.request.method == "GET"

}



reason := "The resource has temporarily moved. Please follow the new URL." if {

  not allow

}



headers := {

  "Location": "http://example.com/auth"

} if {

  not allow

}



status_code := 302 if {

  not allow

}

'
```

创建一个使用 `opa` 插件的路由：

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

    "uri": "/anything",

    "plugins": {

      "opa": {

        "host": "http://opa-server:8181",

        "policy": "customresp"

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

❶ 配置网关可访问的 OPA 服务器地址。

❷ 将授权策略设置为 `customresp`。

adc.yaml

```
services:

  - name: opa-service

    labels:

      docs-example: opa

    routes:

      - name: opa-route

        uris:

          - /anything

        plugins:

          opa:

            host: "http://opa-server:8181"

            policy: customresp

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ 配置网关可访问的 OPA 服务器地址。

❷ 将授权策略设置为 `customresp`。

预览带有示例标签的 Service 变更：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=opa
```

同步已审核的变更：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=opa
```

* Gateway API
* APISIX CRD

opa-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: opa-customresp-plugin-config

spec:

  plugins:

    - name: opa

      config:

        host: "http://opa.aic.svc.cluster.local:8181"

        policy: customresp

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: opa-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: PathPrefix

            value: /anything

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: opa-customresp-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

❶ 配置 OPA 服务器地址。

❷ 将授权策略设置为 `customresp`。

将配置应用到集群：

```
kubectl apply -f opa-ic.yaml
```

opa-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: opa-route

spec:

  ingressClassName: apisix

  http:

    - name: opa-route

      match:

        paths:

          - /anything

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: opa

          enable: true

          config:

            host: "http://opa.aic.svc.cluster.local:8181"

            policy: customresp
```

❶ 配置 OPA 服务器地址。

❷ 将授权策略设置为 `customresp`。

将配置应用到集群：

```
kubectl apply -f opa-ic.yaml
```

向路由发送一个 GET 请求：

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

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

向路由发送一个 POST 请求：

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

你应该收到 `HTTP/1.1 302 Moved Temporarily` 响应：

```
HTTP/1.1 302 Moved Temporarily

...

Location: http://example.com/auth



The resource has temporarily moved. Please follow the new URL.
```

### 实现 RBAC[​](#实现-rbac "实现 RBAC的直接链接")

以下示例组合使用 [`jwt-auth`](https://docs.apiseven.com/hub/jwt-auth.md) 和 `opa` 插件来实施基于角色的访问控制：

* `user` 角色只能读取上游资源。
* `admin` 角色可以读取和写入上游资源。

为两个示例消费者创建 RBAC 的 OPA 策略，其中 `john` 拥有 `user` 角色，`jane` 拥有 `admin` 角色：

```
curl "http://127.0.0.1:8181/v1/policies/rbac" -X PUT \

  -H "Content-Type: text/plain" \

  -d '

package rbac



# 为用户分配角色

user_roles := {

  "john": ["user"],

  "jane": ["admin"]

}



# 将权限映射到 HTTP 方法

permission_methods := {

  "read": "GET",

  "write": "POST"

}



# 分配角色权限

role_permissions := {

  "user": ["read"],

  "admin": ["read", "write"]

}



# 获取 JWT 授权 Token

bearer_token := t if {

  t := input.request.headers.authorization

}



# 解码 Token 以获取角色和权限

token := {"payload": payload} if {

  [_, payload, _] := io.jwt.decode(bearer_token)

}



# 将权限规范化为列表

normalized_permissions := ps if {

  ps := token.payload.permission

  not is_string(ps)

}



normalized_permissions := [ps] if {

  ps := token.payload.permission

  is_string(ps)

}



# 实现 RBAC 逻辑

default result := {"allow": false}



result := {"allow": true} if {

  # 查找用户的角色列表

  roles := user_roles[input.consumer.username]



  # 遍历列表中的每个角色

  r := roles[_]



  # 查找角色的权限列表

  permissions := role_permissions[r]



  # 遍历每项权限

  p := permissions[_]



  # 检查权限是否与请求方法匹配

  permission_methods[p] == input.request.method



  # 检查规范化后的权限是否包含该权限

  p in normalized_permissions

}

'
```

在 APISIX 中创建两个消费者 `john` 和 `jane`，并配置其 `jwt-auth` 凭证：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/consumers" \

  -X PUT \

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

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

  -d '{

    "username": "john"

}'
```

```
curl "http://127.0.0.1:9180/apisix/admin/consumers" \

  -X PUT \

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

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

  -d '{

    "username": "jane"

}'
```

使用默认算法 `HS256` 为消费者配置 `jwt-auth` 凭据：

```
curl "http://127.0.0.1:9180/apisix/admin/consumers/john/credentials" -X PUT \

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

  -d '{

    "id": "cred-john-jwt-auth",

    "plugins": {

      "jwt-auth": {

        "key": "john-key",

        "secret": "john-hs256-secret-that-is-very-long"

      }

    }

  }'
```

```
curl "http://127.0.0.1:9180/apisix/admin/consumers/jane/credentials" -X PUT \

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

  -d '{

    "id": "cred-jane-jwt-auth",

    "plugins": {

      "jwt-auth": {

        "key": "jane-key",

        "secret": "jane-hs256-secret-that-is-very-long"

      }

    }

  }'
```

adc.yaml

```
consumers:

  - username: john

    labels:

      docs-example: opa

    credentials:

      - name: cred-john-jwt-auth

        type: jwt-auth

        config:

          key: john-key

          secret: john-hs256-secret-that-is-very-long

  - username: jane

    labels:

      docs-example: opa

    credentials:

      - name: cred-jane-jwt-auth

        type: jwt-auth

        config:

          key: jane-key

          secret: jane-hs256-secret-that-is-very-long
```

预览 Consumer 变更，包括其嵌套凭据：

```
adc diff -f adc.yaml \

  --include-resource-type consumer \

  --label-selector docs-example=opa
```

同步已审核的变更：

```
adc sync -f adc.yaml \

  --include-resource-type consumer \

  --label-selector docs-example=opa
```

* Gateway API
* APISIX CRD

opa-consumers-ic.yaml

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

kind: Consumer

metadata:

  namespace: aic

  name: john

spec:

  gatewayRef:

    name: apisix

  credentials:

    - type: jwt-auth

      name: cred-john-jwt-auth

      config:

        key: john-key

        secret: john-hs256-secret-that-is-very-long

---

apiVersion: apisix.apache.org/v1alpha1

kind: Consumer

metadata:

  namespace: aic

  name: jane

spec:

  gatewayRef:

    name: apisix

  credentials:

    - type: jwt-auth

      name: cred-jane-jwt-auth

      config:

        key: jane-key

        secret: jane-hs256-secret-that-is-very-long
```

将配置应用到集群：

```
kubectl apply -f opa-consumers-ic.yaml
```

opa-consumers-ic.yaml

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

kind: ApisixConsumer

metadata:

  namespace: aic

  name: john

spec:

  ingressClassName: apisix

  authParameter:

    jwtAuth:

      value:

        key: john-key

        secret: john-hs256-secret-that-is-very-long

---

apiVersion: apisix.apache.org/v2

kind: ApisixConsumer

metadata:

  namespace: aic

  name: jane

spec:

  ingressClassName: apisix

  authParameter:

    jwtAuth:

      value:

        key: jane-key

        secret: jane-hs256-secret-that-is-very-long
```

将配置应用到集群：

```
kubectl apply -f opa-consumers-ic.yaml
```

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

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

    "methods": ["GET", "POST"],

    "uris": ["/get","/post"],

    "plugins": {

      "jwt-auth": {},

      "opa": {

        "host": "http://opa-server:8181",

        "policy": "rbac/result",

        "with_consumer": true

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

❶ 在路由上启用 `jwt-auth` 插件。

❷ 配置网关可访问的 OPA 服务器地址。

❸ 将授权策略设置为 `rbac/result`。

❹ 将 `with_consumer` 设置为 `true`，以发送消费者信息。

更新 `adc.yaml`，添加启用了 `jwt-auth` 和 `opa` 插件的路由：

adc.yaml

```
consumers:

  - username: john

    credentials:

      - name: cred-john-jwt-auth

        type: jwt-auth

        config:

          key: john-key

          secret: john-hs256-secret-that-is-very-long

  - username: jane

    credentials:

      - name: cred-jane-jwt-auth

        type: jwt-auth

        config:

          key: jane-key

          secret: jane-hs256-secret-that-is-very-long

services:

  - name: opa-service

    labels:

      docs-example: opa

    routes:

      - name: opa-route

        uris:

          - /get

          - /post

        methods:

          - GET

          - POST

        plugins:

          jwt-auth: {}

          opa:

            host: "http://opa-server:8181"

            policy: rbac/result

            with_consumer: true

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

❶ 在路由上启用 `jwt-auth` 插件。

❷ 配置网关可访问的 OPA 服务器地址。

❸ 将授权策略设置为 `rbac/result`。

❹ 将 `with_consumer` 设置为 `true`，以发送消费者信息。

预览带有示例标签的 Service 变更：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=opa
```

同步已审核的变更：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=opa
```

* Gateway API
* APISIX CRD

opa-route-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: opa-rbac-plugin-config

spec:

  plugins:

    - name: jwt-auth

      config:

        _meta:

          disable: false

    - name: opa

      config:

        host: "http://opa.aic.svc.cluster.local:8181"

        policy: rbac/result

        with_consumer: true

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: opa-rbac-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /get

          method: GET

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: opa-rbac-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80

    - matches:

        - path:

            type: Exact

            value: /post

          method: POST

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: opa-rbac-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

❶ 配置 OPA 服务器地址。

❷ 将授权策略设置为 `rbac/result`。

❸ 将 `with_consumer` 设置为 `true`，以发送消费者信息。

将配置应用到集群：

```
kubectl apply -f opa-route-ic.yaml
```

备注

使用 Ingress Controller 时，APISIX 会为消费者名称添加 Kubernetes 命名空间前缀。例如，`aic` 命名空间中名为 `john` 的消费者会变为 `aic_john`。请更新 OPA RBAC 策略以使用带前缀的名称：

```
curl "http://127.0.0.1:8181/v1/policies/rbac" -X PUT \

  -H "Content-Type: text/plain" \

  -d '

package rbac



# 为用户分配角色

user_roles := {

  "aic_john": ["user"],

  "aic_jane": ["admin"]

}



# 将权限映射到 HTTP 方法

permission_methods := {

  "read": "GET",

  "write": "POST"

}



# 分配角色权限

role_permissions := {

  "user": ["read"],

  "admin": ["read", "write"]

}



# 获取 JWT 授权 Token

bearer_token := t if {

  t := input.request.headers.authorization

}



# 解码 Token 以获取角色和权限

token := {"payload": payload} if {

  [_, payload, _] := io.jwt.decode(bearer_token)

}



# 将权限规范化为列表

normalized_permissions := ps if {

  ps := token.payload.permission

  not is_string(ps)

}



normalized_permissions := [ps] if {

  ps := token.payload.permission

  is_string(ps)

}



# 实现 RBAC 逻辑

default result := {"allow": false}



result := {"allow": true} if {

  # 查找用户的角色列表

  roles := user_roles[input.consumer.username]



  # 遍历列表中的每个角色

  r := roles[_]



  # 查找角色的权限列表

  permissions := role_permissions[r]



  # 遍历每项权限

  p := permissions[_]



  # 检查权限是否与请求方法匹配

  permission_methods[p] == input.request.method



  # 检查规范化后的权限是否包含该权限

  p in normalized_permissions

}

'
```

opa-route-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: opa-rbac-route

spec:

  ingressClassName: apisix

  http:

    - name: get-route

      match:

        methods:

          - GET

        paths:

          - /get

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: jwt-auth

          enable: true

          config:

            _meta:

              disable: false

        - name: opa

          enable: true

          config:

            host: "http://opa.aic.svc.cluster.local:8181"

            policy: rbac/result

            with_consumer: true

    - name: post-route

      match:

        methods:

          - POST

        paths:

          - /post

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: jwt-auth

          enable: true

          config:

            _meta:

              disable: false

        - name: opa

          enable: true

          config:

            host: "http://opa.aic.svc.cluster.local:8181"

            policy: rbac/result

            with_consumer: true
```

将配置应用到集群：

```
kubectl apply -f opa-route-ic.yaml
```

备注

使用 Ingress Controller 时，APISIX 会为消费者名称添加 Kubernetes 命名空间前缀。例如，`aic` 命名空间中名为 `john` 的消费者会变为 `aic_john`。请更新 OPA RBAC 策略以使用带前缀的名称：

```
curl "http://127.0.0.1:8181/v1/policies/rbac" -X PUT \

  -H "Content-Type: text/plain" \

  -d '

package rbac



user_roles := {

  "aic_john": ["user"],

  "aic_jane": ["admin"]

}



permission_methods := {

  "read": "GET",

  "write": "POST"

}



role_permissions := {

  "user": ["read"],

  "admin": ["read", "write"]

}



bearer_token := t if {

  t := input.request.headers.authorization

}



token := {"payload": payload} if {

  [_, payload, _] := io.jwt.decode(bearer_token)

}



normalized_permissions := ps if {

  ps := token.payload.permission

  not is_string(ps)

}



normalized_permissions := [ps] if {

  ps := token.payload.permission

  is_string(ps)

}



default result := {"allow": false}



result := {"allow": true} if {

  roles := user_roles[input.consumer.username]

  r := roles[_]

  permissions := role_permissions[r]

  p := permissions[_]

  permission_methods[p] == input.request.method

  p in normalized_permissions

}

'
```

#### 在本地生成 JWT[​](#在本地生成-jwt "在本地生成 JWT的直接链接")

在当前 Shell 中定义 HS256 辅助函数：

```
base64url() {

  openssl base64 -A | tr '+/' '-_' | tr -d '='

}



sign_hs256() {

  local secret="$1"

  local payload="$2"

  local encoded_header encoded_payload signature



  encoded_header=$(printf '%s' '{"alg":"HS256","typ":"JWT"}' | base64url)

  encoded_payload=$(printf '%s' "$payload" | base64url)

  signature=$(printf '%s' "$encoded_header.$encoded_payload" | \

    openssl dgst -sha256 -hmac "$secret" -binary | base64url)



  printf '%s.%s.%s\n' "$encoded_header" "$encoded_payload" "$signature"

}
```

为确保测试可重复执行，这些本地 Token 省略了过期声明。生产 Token 应使用较短的 `exp` 有效期。

#### 验证 `john`[​](#验证-john "验证-john的直接链接")

使用配置的密钥、Secret 和授权声明生成 `john` 的 Token：

```
john_jwt_token=$(sign_hs256 \

  'john-hs256-secret-that-is-very-long' \

  '{"role":"user","permission":"read","key":"john-key"}')

export john_jwt_token
```

使用 `john` 的 JWT 向路由发送 GET 请求：

```
curl -i "http://127.0.0.1:9080/get" -H "Authorization: ${john_jwt_token}"
```

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

使用相同的 JWT 向路由发送 POST 请求：

```
curl -i "http://127.0.0.1:9080/post" -X POST -H "Authorization: ${john_jwt_token}"
```

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

#### 验证 `jane`[​](#验证-jane "验证-jane的直接链接")

使用配置的密钥、Secret 和授权声明生成 `jane` 的 Token：

```
jane_jwt_token=$(sign_hs256 \

  'jane-hs256-secret-that-is-very-long' \

  '{"role":"admin","permission":["read","write"],"key":"jane-key"}')

export jane_jwt_token
```

使用 `jane` 的 JWT 向路由发送 GET 请求：

```
curl -i "http://127.0.0.1:9080/get" -H "Authorization: ${jane_jwt_token}"
```

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

使用相同的 JWT 向路由发送 POST 请求：

```
curl -i "http://127.0.0.1:9080/post" -X POST -H "Authorization: ${jane_jwt_token}"
```

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

提示

要验证授权决策，请检查 OPA 服务器的 `Sent response.` 日志条目。使用 `--log-level debug` 时，解码后的 `resp_body` 值应包含：

```
{

  "result": {

    "allow": true

  }

}
```
