# Authz Casdoor

The `authz-casdoor` plugin protects routes with [Casdoor](https://casdoor.org/) sign-in. When a user without an authenticated gateway session requests a protected route, the plugin redirects the browser to Casdoor.

After Casdoor returns an authorization code, the plugin exchanges it for an access token. It stores the token in an encrypted browser session and sends the user back to the original URI.

## Example[​](#example "Direct link to Example")

The following example starts Casdoor, registers the gateway as an OAuth application, and protects an HTTPBin route. It uses local credentials and HTTP only for testing.

Before starting, configure one worker process on every gateway instance and enable instance affinity as described in [Static Configurations](https://docs.api7.ai/hub/authz-casdoor/configuration.md#static-configurations).

### Protect an HTTPBin Route with Casdoor[​](#protect-an-httpbin-route-with-casdoor "Direct link to Protect an HTTPBin Route with Casdoor")

This workflow deploys Casdoor, registers the gateway application, configures the protected route, and verifies the authenticated session.

#### Start Casdoor[​](#start-casdoor "Direct link to Start Casdoor")

Start Casdoor in the environment that matches the gateway deployment.

* Docker
* Kubernetes

Install [Docker](https://docs.docker.com/get-docker/) and complete the [Getting Started tutorial](https://docs.api7.ai/apisix/getting-started.md) before continuing.

Map `casdoor.local` to `127.0.0.1` in the hosts file on the computer running the browser. Start the official all-in-one Casdoor image on the quickstart network:

```
docker run -d --name apisix-casdoor \

  --network apisix-quickstart-net \

  --network-alias casdoor.local \

  -p 127.0.0.1:8000:8000 \

  casbin/casdoor-all-in-one@sha256:710df7fcb2d05ddc590cf78a6862ec61026a140c1a02ec6a40392dc24dabf7f9
```

The network alias lets the gateway reach the same `http://casdoor.local:8000` address that the browser opens.

Use a Kubernetes cluster with `kubectl` access. Create `casdoor.yaml`:

casdoor.yaml

```
apiVersion: apps/v1

kind: Deployment

metadata:

  namespace: aic

  name: casdoor

spec:

  replicas: 1

  selector:

    matchLabels:

      app: casdoor

  template:

    metadata:

      labels:

        app: casdoor

    spec:

      containers:

        - name: casdoor

          image: casbin/casdoor-all-in-one@sha256:710df7fcb2d05ddc590cf78a6862ec61026a140c1a02ec6a40392dc24dabf7f9

          ports:

            - containerPort: 8000

          readinessProbe:

            httpGet:

              path: /api/health

              port: 8000

            initialDelaySeconds: 20

            periodSeconds: 10

---

apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: casdoor

spec:

  type: LoadBalancer

  selector:

    app: casdoor

  ports:

    - port: 8000

      targetPort: 8000
```

Apply the manifest and wait for Casdoor to become available:

```
kubectl create namespace aic --dry-run=client -o yaml | kubectl apply -f -

kubectl apply -f casdoor.yaml

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

Publish the Service at a DNS name that browsers and gateway pods can both resolve, such as `casdoor.example.com`.

The all-in-one image is intended for evaluation. For production, deploy Casdoor with persistent storage, an external production database, TLS, backups, and high-availability settings appropriate for the environment.

Set the Casdoor, gateway, and callback URLs for the selected runtime:

* Docker
* Kubernetes

```
export CASDOOR_URL="http://casdoor.local:8000"

export GATEWAY_URL="http://127.0.0.1:9080"

export CASDOOR_CALLBACK_URL="http://127.0.0.1:9080/callback"
```

Replace the example domains with the public Casdoor and gateway domains:

```
export CASDOOR_URL="http://casdoor.example.com:8000"

export GATEWAY_URL="http://api.example.com"

export CASDOOR_CALLBACK_URL="http://api.example.com/callback"
```

#### Configure Casdoor[​](#configure-casdoor "Direct link to Configure Casdoor")

Initialize a password for the built-in administrator in this new Casdoor installation:

```
curl "${CASDOOR_URL}/api/init-admin-password" -X POST \

  -F "password=admin123"
```

The response confirms that the administrator password was initialized:

```
{

  "status": "ok",

  "msg": "",

  "sub": "",

  "name": "",

  "data": null,

  "data2": null,

  "data3": null

}
```

In a browser, open the URL exported as `CASDOOR_URL` and sign in to the `built-in` organization with username `admin` and password `admin123`. Create an application for the gateway:

1. Open **Applications** and select **Add**.
2. Enter `app-authz-casdoor` as the name and select `built-in` as the organization.
3. Add the value exported as `CASDOOR_CALLBACK_URL` to **Redirect URLs**.
4. Save the application, then copy its client ID and client secret.

Export the application credentials. Replace the placeholder values with those generated by Casdoor:

```
export CASDOOR_CLIENT_ID="replace-with-client-id"

export CASDOOR_CLIENT_SECRET="replace-with-client-secret"
```

The built-in administrator is used only to make the local flow reproducible. Create ordinary users and apply the organization's sign-in policies before using the integration in another environment.

#### Configure the Gateway[​](#configure-the-gateway "Direct link to Configure the Gateway")

The protected route matches both `/anything/*` and the `/callback` path registered in Casdoor. Choose the API used to configure the route.

* Admin API
* ADC
* Ingress Controller

Create the protected route:

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

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

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

  -d @- <<EOF

{

  "uris": [

    "/anything/*",

    "/callback"

  ],

  "plugins": {

    "authz-casdoor": {

      "endpoint_addr": "${CASDOOR_URL}",

      "client_id": "${CASDOOR_CLIENT_ID}",

      "client_secret": "${CASDOOR_CLIENT_SECRET}",

      "callback_url": "${CASDOOR_CALLBACK_URL}"

    }

  },

  "upstream": {

    "type": "roundrobin",

    "nodes": {

      "httpbin.org:80": 1

    }

  }

}

EOF
```

[Install and configure ADC](https://docs.api7.ai/apisix/reference/adc.md) before continuing.

Create `adc.yaml`:

adc.yaml

```
services:

  - name: authz-casdoor-httpbin

    labels:

      docs-example: authz-casdoor

    routes:

      - name: authz-casdoor

        uris:

          - /anything/*

          - /callback

        plugins:

          authz-casdoor:

            endpoint_addr: "${CASDOOR_URL}"

            client_id: "${CASDOOR_CLIENT_ID}"

            client_secret: "${CASDOOR_CLIENT_SECRET}"

            callback_url: "${CASDOOR_CALLBACK_URL}"

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

Preview the changes:

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

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

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

[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. Replace the Casdoor URL, client ID, client secret, callback URL, and public hostname in either manifest.

* Gateway API
* APISIX CRD

Create `authz-casdoor-ic.yaml`:

authz-casdoor-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: authz-casdoor

spec:

  plugins:

    - name: authz-casdoor

      config:

        endpoint_addr: http://casdoor.example.com:8000

        client_id: replace-with-client-id

        client_secret: replace-with-client-secret

        callback_url: http://api.example.com/callback

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: authz-casdoor

spec:

  parentRefs:

    - name: apisix

  hostnames:

    - api.example.com

  rules:

    - matches:

        - path:

            type: PathPrefix

            value: /anything/

        - path:

            type: Exact

            value: /callback

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: authz-casdoor

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

Apply the manifest:

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

Create `authz-casdoor-ic.yaml`:

authz-casdoor-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: authz-casdoor

spec:

  ingressClassName: apisix

  http:

    - name: authz-casdoor

      match:

        hosts:

          - api.example.com

        paths:

          - /anything/*

          - /callback

      upstreams:

        - name: httpbin-external-domain

      plugins:

        - name: authz-casdoor

          enable: true

          config:

            endpoint_addr: http://casdoor.example.com:8000

            client_id: replace-with-client-id

            client_secret: replace-with-client-secret

            callback_url: http://api.example.com/callback
```

Apply the manifest:

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

#### Verify the Sign-In Flow[​](#verify-the-sign-in-flow "Direct link to Verify the Sign-In Flow")

In a browser, open the gateway URL exported as `GATEWAY_URL` with the `/anything/authz-casdoor` path. Casdoor should prompt for credentials. Sign in to the `built-in` organization with username `admin` and password `admin123`.

Casdoor returns the browser to `/callback`. The gateway exchanges the authorization code, redirects the browser to the original URI, and proxies the request. The response should contain the HTTPBin request details. The Docker response is similar to:

```
{

  "args": {},

  "method": "GET",

  "url": "http://127.0.0.1/anything/authz-casdoor"

}
```

For Kubernetes, the `url` value uses the public gateway origin.

Reload the same URL. The gateway should reuse the authenticated session without redirecting to Casdoor until the access token expires. After it expires, the next protected request starts a new sign-in flow.

The plugin validates that the callback contains the state created for the same browser session. A callback with a missing or changed code or state is rejected with `400 Bad Request`.

The gateway returns `503 Service Unavailable` when a callback has no readable session or the authorization-code exchange fails. Failures include an unreachable Casdoor server, a response without an access token, and a token response with a missing, zero, or negative lifetime. The gateway records the reason in its error log.

## Production Considerations[​](#production-considerations "Direct link to Production Considerations")

Use HTTPS for Casdoor, the gateway, and the callback URL. Register a separate Casdoor application for each environment, keep its client secret outside source control, and configure a callback URL that cannot be redirected to an untrusted host.

The Casdoor address must be reachable from the browser and every gateway instance. The browser opens the authorization endpoint, while the gateway calls the token endpoint.

The plugin does not provide a logout endpoint or refresh access tokens. A session remains valid until its Casdoor access token expires or the gateway session cookie is removed. The next protected request then starts a new sign-in flow.

The plugin uses the access token only to maintain the gateway session. It does not add the token, Casdoor user profile, or identity headers to the upstream request. Use another integration if the upstream service needs a bearer token or verified user attributes.
