# Casbin 授权

`authz-casbin` 插件在请求到达上游之前，使用 [Casbin](https://casbin.org/) 模型和策略对请求进行授权。它可以为单条路由应用策略，也可以在多条路由间复用共享策略，支持基于角色及其他 Casbin 访问控制模型。

## 授权行为[​](#authorization-behavior "授权行为的直接链接")

插件依据配置的策略评估以下三个请求值：

| Casbin 值 | 请求值                                           |
| --------- | ------------------------------------------------ |
| 主体      | 配置的请求头的值；请求头不存在时为 `anonymous`。 |
| 对象      | 规范化后的请求路径。                             |
| 操作      | HTTP 请求方法。                                  |

获准的请求会继续转发到上游。被拒绝的请求返回 `403 Forbidden`，并附带 `Access Denied` 消息。

插件直接将配置的请求头值用作主体，不会对该值进行身份认证。在生产环境中，应确保该值由可信组件设置，且客户端无法覆盖它。

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

第一个示例在单条路由上配置基于角色的策略。第二个示例将策略移至插件元数据，以便复用策略，并独立于路由进行更新。

为示例创建工作目录并进入该目录。

```
mkdir authz-casbin-example

cd authz-casbin-example
```

如果启用了 Admin API 身份验证，请在使用 **Admin API** 标签页前将具有管理员角色的密钥导出为 `ADMIN_API_KEY`。

### 在单条路由上为角色授权[​](#authorize-a-role-on-one-route "在单条路由上为角色授权的直接链接")

示例策略授予 reader 角色向 `/anything/` 下的路径发送 GET 请求的权限，并将该角色分配给 Alice。

创建 Casbin 模型：

model.conf

```
[request_definition]

r = sub, obj, act



[policy_definition]

p = sub, obj, act



[role_definition]

g = _, _



[policy_effect]

e = some(where (p.eft == allow))



[matchers]

m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && keyMatch(r.act, p.act)
```

创建策略：

policy.csv

```
p, reader, /anything/*, GET

g, alice, reader
```

* Admin API
* ADC
* Ingress Controller

创建路由，将模型和策略以文本形式嵌入其中：

```
jq -n \

  --rawfile model model.conf \

  --rawfile policy policy.csv \

  '{

    uri: "/anything/*",

    plugins: {

      "authz-casbin": {

        model: $model,

        policy: $policy,

        username: "x-user"

      }

    },

    upstream: {

      type: "roundrobin",

      nodes: {

        "httpbin.org:80": 1

      }

    }

  }' | \

  curl "http://127.0.0.1:9180/apisix/admin/routes/authz-casbin-route" -X PUT \

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

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

    --data-binary @-
```

配置 ADC 以连接目标后端。后续 ADC 命令会从这些环境变量读取连接设置。

* APISIX
* API7 网关

如果启用了 Admin API 身份验证，请在配置 ADC 前将具有管理员角色的密钥导出为 `ADMIN_API_KEY`。

```
export ADC_BACKEND=apisix

export ADC_SERVER="http://127.0.0.1:9180"

export ADC_TOKEN="${ADMIN_API_KEY}"
```

```
export ADC_BACKEND=api7ee

export ADC_SERVER="https://{DASHBOARD_ADDR}"

export ADC_TOKEN="{DASHBOARD_TOKEN}"

export ADC_GATEWAY_GROUP="{GATEWAY_GROUP}"
```

创建服务和路由。

adc.yaml

```
services:

  - name: authz-casbin-service

    labels:

      docs-example: authz-casbin

    routes:

      - name: authz-casbin-route

        uris:

          - /anything/*

        plugins:

          authz-casbin:

            model: |

              [request_definition]

              r = sub, obj, act



              [policy_definition]

              p = sub, obj, act



              [role_definition]

              g = _, _



              [policy_effect]

              e = some(where (p.eft == allow))



              [matchers]

              m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && keyMatch(r.act, p.act)

            policy: |

              p, reader, /anything/*, GET

              g, alice, reader

            username: x-user

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

预览改动，确认仅影响本示例的资源。

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=authz-casbin
```

核对 `diff.yaml`，再同步带有此标签的服务。

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=authz-casbin
```

继续之前，先在 `aic` 命名空间中[设置 Ingress Controller 和网关](https://docs.apiseven.com/ingress-controller/set-up-ingress-controller-and-gateway.md)。

使用 Gateway API 或 APISIX 自定义资源配置内联模型和策略：

* Gateway API
* APISIX CRD

authz-casbin-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: authz-casbin-plugin-config

spec:

  plugins:

    - name: authz-casbin

      config:

        model: |

          [request_definition]

          r = sub, obj, act



          [policy_definition]

          p = sub, obj, act



          [role_definition]

          g = _, _



          [policy_effect]

          e = some(where (p.eft == allow))



          [matchers]

          m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && keyMatch(r.act, p.act)

        policy: |

          p, reader, /anything/*, GET

          g, alice, reader

        username: x-user

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: authz-casbin-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: PathPrefix

            value: /anything/

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: authz-casbin-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

authz-casbin-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: ApisixPluginConfig

metadata:

  namespace: aic

  name: authz-casbin-plugin-config

spec:

  ingressClassName: apisix

  plugins:

    - name: authz-casbin

      enable: true

      config:

        model: |

          [request_definition]

          r = sub, obj, act



          [policy_definition]

          p = sub, obj, act



          [role_definition]

          g = _, _



          [policy_effect]

          e = some(where (p.eft == allow))



          [matchers]

          m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && keyMatch(r.act, p.act)

        policy: |

          p, reader, /anything/*, GET

          g, alice, reader

        username: x-user

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: authz-casbin-route

spec:

  ingressClassName: apisix

  http:

    - name: authz-casbin-route

      match:

        paths:

          - /anything/*

      upstreams:

        - name: httpbin-external-domain

      plugin_config_name: authz-casbin-plugin-config
```

应用配置：

```
kubectl apply -f authz-casbin-ic.yaml
```

以 Alice 的身份发送请求：

```
curl "http://127.0.0.1:9080/anything/article" \

  -H "X-User: alice" \

  --silent \

  --output /dev/null \

  --write-out "Allowed response: %{http_code}\n"
```

分配的角色允许该请求到达上游：

```
Allowed response: 200
```

以 Bob 的身份发送相同的请求：

```
curl --include "http://127.0.0.1:9080/anything/article" \

  -H "X-User: bob"
```

策略拒绝该请求：

```
HTTP/1.1 403 Forbidden

...

{"message":"Access Denied"}
```

### 通过插件元数据共享策略[​](#share-a-policy-with-plugin-metadata "通过插件元数据共享策略的直接链接")

[插件元数据](https://docs.apiseven.com/apisix/key-concepts/plugin-metadata.md)使多条路由可以复用同一组模型和策略。更新第一个示例中的策略，将 reader 角色分配给 Bob，然后配置路由以读取共享策略。

仅配置主体请求头的路由依赖完整的模型和策略元数据。如果元数据缺失，网关将返回 `503 Service Unavailable`，不会访问上游。

更新 `policy.csv`：

policy.csv

```
p, reader, /anything/*, GET

g, bob, reader
```

* Admin API
* ADC
* Ingress Controller

将模型和更新后的策略存储到插件元数据：

```
jq -n \

  --rawfile model model.conf \

  --rawfile policy policy.csv \

  '{model: $model, policy: $policy}' | \

  curl "http://127.0.0.1:9180/apisix/admin/plugin_metadata/authz-casbin" -X PUT \

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

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

    --data-binary @-
```

将路由级别的模型和策略替换为请求头选择配置：

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

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

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

  -d '{

    "username": "x-user"

  }'
```

导出完整的插件元数据集合：

```
adc dump -o metadata.yaml \

  --with-id \

  --include-resource-type plugin_metadata
```

在导出的 `plugin_metadata` 映射下添加或更新此条目，并保留其他所有条目：

metadata.yaml (plugin\_metadata excerpt)

```
plugin_metadata:

  authz-casbin:

    model: |

      [request_definition]

      r = sub, obj, act



      [policy_definition]

      p = sub, obj, act



      [role_definition]

      g = _, _



      [policy_effect]

      e = some(where (p.eft == allow))



      [matchers]

      m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && keyMatch(r.act, p.act)

    policy: |

      p, reader, /anything/*, GET

      g, bob, reader
```

预览完整的插件元数据集合，确认没有意外更新或删除：

```
adc diff -f metadata.yaml \

  --include-resource-type plugin_metadata
```

同步已检查的插件元数据：

```
adc sync -f metadata.yaml \

  --include-resource-type plugin_metadata
```

在 `adc.yaml` 中替换现有路由上的插件配置：

adc.yaml (route plugin)

```
plugins:

  authz-casbin:

    username: x-user
```

预览更新后的服务：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=authz-casbin
```

核对 `diff.yaml`，再同步带有此标签的服务。

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=authz-casbin
```

在部署所使用的完整 `GatewayProxy` 清单的 `spec.pluginMetadata` 下添加共享模型和策略。保留其他所有元数据条目：

gatewayproxy.yaml (spec excerpt)

```
spec:

  pluginMetadata:

    authz-casbin:

      model: |

        [request_definition]

        r = sub, obj, act



        [policy_definition]

        p = sub, obj, act



        [role_definition]

        g = _, _



        [policy_effect]

        e = some(where (p.eft == allow))



        [matchers]

        m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && keyMatch(r.act, p.act)

      policy: |

        p, reader, /anything/*, GET

        g, bob, reader
```

通过部署常用的 Kubernetes 或 GitOps 工作流应用完整的 `GatewayProxy` 清单。

更新路由引用的插件配置，使其使用共享策略：

* Gateway API
* APISIX CRD

authz-casbin-plugin-config.yaml

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

kind: PluginConfig

metadata:

  namespace: aic

  name: authz-casbin-plugin-config

spec:

  plugins:

    - name: authz-casbin

      config:

        username: x-user
```

authz-casbin-plugin-config.yaml

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

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: authz-casbin-plugin-config

spec:

  ingressClassName: apisix

  plugins:

    - name: authz-casbin

      enable: true

      config:

        username: x-user
```

应用更新后的插件配置：

```
kubectl apply -f authz-casbin-plugin-config.yaml
```

再次以 Bob 的身份发送请求：

```
curl "http://127.0.0.1:9080/anything/article" \

  -H "X-User: bob" \

  --silent \

  --output /dev/null \

  --write-out "Allowed response: %{http_code}\n"
```

共享策略现在允许 Bob 的请求到达上游：

```
Allowed response: 200
```

发送不带所配置身份请求头的请求：

```
curl --include "http://127.0.0.1:9080/anything/article"
```

插件将该请求视为匿名主体并拒绝请求：

```
HTTP/1.1 403 Forbidden

...

{"message":"Access Denied"}
```
