# Casbin Authorization

The `authz-casbin` plugin authorizes requests with [Casbin](https://casbin.org/) models and policies before they reach an upstream. It can apply a policy to one route or reuse a shared policy across routes, supporting role-based and other Casbin access-control models.

## Authorization Behavior[​](#authorization-behavior "Direct link to Authorization Behavior")

The plugin evaluates three request values against the configured policy:

| Casbin value | Request value                                                                     |
| ------------ | --------------------------------------------------------------------------------- |
| Subject      | Value of the configured request header, or `anonymous` when the header is absent. |
| Object       | Normalized request path.                                                          |
| Action       | HTTP request method.                                                              |

An allowed request continues to the upstream. A denied request returns `403 Forbidden` with an `Access Denied` message.

The plugin uses the configured header value as the subject without authenticating it. In production, ensure that a trusted component establishes the value and that clients cannot override it.

## Examples[​](#examples "Direct link to Examples")

The examples first configure a role-based policy on one route. The second example moves the policy to plugin metadata so that it can be reused and updated independently of the route.

Create and enter a working directory for the example:

```
mkdir authz-casbin-example

cd authz-casbin-example
```

If Admin API authentication is enabled, export an admin-role key as `ADMIN_API_KEY` before using the Admin API tab.

### Authorize a Role on One Route[​](#authorize-a-role-on-one-route "Direct link to Authorize a Role on One Route")

The example policy gives the reader role permission to send GET requests to paths under `/anything/` and assigns that role to Alice.

Create the Casbin model:

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

Create the policy:

policy.csv

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

g, alice, reader
```

* Admin API
* ADC
* Ingress Controller

Create the route with the model and policy embedded as text:

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

Configure ADC to connect to the target backend. The remaining ADC commands read the connection settings from these environment variables:

* APISIX
* API7 Gateway

If Admin API authentication is enabled, export an admin-role key as `ADMIN_API_KEY` before configuring ADC.

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

Create the service and route:

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

Preview the changes and confirm that they only affect resources for this example:

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

Review `diff.yaml`, then synchronize the labeled service:

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

[Set up the Ingress Controller and gateway](https://docs.api7.ai/ingress-controller/set-up-ingress-controller-and-gateway.md) in the `aic` namespace before continuing.

Configure the inline model and policy with either Gateway API or APISIX custom resources:

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

Apply the configuration:

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

Send a request as 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"
```

The assigned role allows the request to reach the upstream:

```
Allowed response: 200
```

Send the same request as Bob:

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

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

The policy denies the request:

```
HTTP/1.1 403 Forbidden

...

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

### Share a Policy with Plugin Metadata[​](#share-a-policy-with-plugin-metadata "Direct link to Share a Policy with Plugin Metadata")

[Plugin metadata](https://docs.api7.ai/apisix/key-concepts/plugin-metadata.md) lets routes reuse one model and policy. Update the policy from the first example to assign the reader role to Bob, then configure the route to read the shared policy.

A route configured with only the subject header depends on complete model and policy metadata. If that metadata is missing, the gateway returns `503 Service Unavailable` without contacting the upstream.

Update `policy.csv`:

policy.csv

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

g, bob, reader
```

* Admin API
* ADC
* Ingress Controller

Store the model and updated policy in plugin metadata:

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

Replace the route-level model and policy with the header selection:

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

  }'
```

Export the complete plugin metadata collection:

```
adc dump -o metadata.yaml \

  --with-id \

  --include-resource-type plugin_metadata
```

Add or update this entry under the exported `plugin_metadata` mapping while preserving every other entry:

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

Preview the complete plugin metadata collection and confirm that it contains no unintended updates or deletions:

```
adc diff -f metadata.yaml \

  --include-resource-type plugin_metadata
```

Synchronize the reviewed plugin metadata:

```
adc sync -f metadata.yaml \

  --include-resource-type plugin_metadata
```

In `adc.yaml`, replace the plugin configuration on the existing route:

adc.yaml (route plugin)

```
plugins:

  authz-casbin:

    username: x-user
```

Preview the updated service:

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

Review `diff.yaml`, then synchronize the labeled service:

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

Add the shared model and policy under `spec.pluginMetadata` in the complete `GatewayProxy` manifest used by the deployment. Preserve every other metadata entry:

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

Apply the complete `GatewayProxy` manifest through the deployment's normal Kubernetes or GitOps workflow.

Update the plugin configuration referenced by the route so that it uses the shared policy:

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

Apply the updated plugin configuration:

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

Send the request as Bob again:

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

  -H "X-User: bob" \

  --silent \

  --output /dev/null \

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

The shared policy now allows Bob to reach the upstream:

```
Allowed response: 200
```

Send a request without the configured identity header:

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

The plugin evaluates the request as the anonymous subject and denies it:

```
HTTP/1.1 403 Forbidden

...

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