# CAS Auth

The `cas-auth` plugin makes the gateway a CAS 2.0 service provider. It redirects unauthenticated users to a CAS identity provider, validates the returned service ticket, and creates a session before sending the original request upstream. The plugin also supports service provider-initiated logout and CAS single logout callbacks.

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

The examples use a small local CAS service with one accepted test ticket to authenticate a session and verify service provider-initiated logout.

### Start a Mock CAS Server[​](#start-a-mock-cas-server "Direct link to Start a Mock CAS Server")

Choose the environment for the mock CAS service.

Create and enter a working directory for the example:

```
mkdir cas-auth-example

cd cas-auth-example
```

Create the mock CAS service:

cas-server.py

```
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from urllib.parse import parse_qs, urlparse





class Handler(BaseHTTPRequestHandler):

    protocol_version = "HTTP/1.1"



    def do_GET(self):

        parsed = urlparse(self.path)



        if parsed.path == "/cas/serviceValidate":

            ticket = parse_qs(parsed.query).get("ticket", [""])[0]

            if ticket == "ST-docs-alice":

                body = b"""<?xml version="1.0"?>

<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">

  <cas:authenticationSuccess>

    <cas:user>alice</cas:user>

  </cas:authenticationSuccess>

</cas:serviceResponse>

"""

            else:

                body = b"""<?xml version="1.0"?>

<cas:serviceResponse xmlns:cas="http://www.yale.edu/tp/cas">

  <cas:authenticationFailure code="INVALID_TICKET">

    Invalid ticket

  </cas:authenticationFailure>

</cas:serviceResponse>

"""

            self.send_response(200)

            self.send_header("Content-Type", "application/xml")

        elif parsed.path in ("/cas/login", "/cas/logout"):

            body = b"Mock CAS endpoint\n"

            self.send_response(200)

            self.send_header("Content-Type", "text/plain")

        else:

            body = b"Not found\n"

            self.send_response(404)

            self.send_header("Content-Type", "text/plain")



        self.send_header("Content-Length", str(len(body)))

        self.end_headers()

        self.wfile.write(body)



    def log_message(self, *_):

        pass





ThreadingHTTPServer(("0.0.0.0", 18082), Handler).serve_forever()
```

* Docker
* Kubernetes

Set `GATEWAY_CONTAINER` to the running APISIX or API7 Gateway container. Create a dedicated network and connect the gateway to it:

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



docker network create gateway-cas-auth-doc-net

docker network connect gateway-cas-auth-doc-net "$GATEWAY_CONTAINER"
```

Start the mock identity provider:

```
docker run -d \

  --name cas-auth-doc-idp \

  --network gateway-cas-auth-doc-net \

  -v "$PWD/cas-server.py:/cas-server.py:ro" \

  python:3.13.15-alpine3.24 \

  python -u /cas-server.py
```

[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.

Create a ConfigMap from the mock CAS script:

```
kubectl create configmap cas-auth-doc-script \

  -n aic \

  --from-file=cas-server.py \

  --dry-run=client \

  -o yaml | kubectl apply -f -
```

Deploy the mock identity provider:

cas-auth-upstream.yaml

```
apiVersion: apps/v1

kind: Deployment

metadata:

  namespace: aic

  name: cas-auth-doc-idp

spec:

  replicas: 1

  selector:

    matchLabels:

      app: cas-auth-doc-idp

  template:

    metadata:

      labels:

        app: cas-auth-doc-idp

    spec:

      containers:

        - name: idp

          image: python:3.13.15-alpine3.24

          command:

            - python

            - -u

            - /app/cas-server.py

          ports:

            - containerPort: 18082

          volumeMounts:

            - name: script

              mountPath: /app/cas-server.py

              subPath: cas-server.py

              readOnly: true

      volumes:

        - name: script

          configMap:

            name: cas-auth-doc-script

---

apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: cas-auth-doc-idp

spec:

  selector:

    app: cas-auth-doc-idp

  ports:

    - port: 18082

      targetPort: 18082
```

Apply the identity-provider configuration:

```
kubectl apply -f cas-auth-upstream.yaml

kubectl rollout status -n aic deployment/cas-auth-doc-idp
```

The fixed ticket in this local example is for testing only.

### Authenticate a CAS Session[​](#authenticate-a-cas-session "Direct link to Authenticate a CAS Session")

Configure a protected route whose callback and logout paths are covered by the same route. The absolute callback URL keeps the CAS service URL independent of the incoming Host header.

* Admin API
* ADC
* Ingress Controller

Create the route:

```
curl "http://127.0.0.1:9180/apisix/admin/routes/cas-auth-doc-route" -X PUT \

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

  -d '{

    "methods": [

      "GET",

      "POST"

    ],

    "host": "cas-auth-doc.local",

    "uri": "/*",

    "plugins": {

      "cas-auth": {

        "idp_uri": "http://cas-auth-doc-idp:18082/cas",

        "cas_callback_uri": "http://cas-auth-doc.local:9080/cas/callback",

        "logout_uri": "/cas/logout",

        "cookie": {

          "secret": "replace-with-a-random-secret-at-least-32-characters",

          "secure": false

        }

      }

    },

    "upstream": {

      "type": "roundrobin",

      "pass_host": "node",

      "nodes": {

        "httpbin.org:80": 1

      }

    }

  }'
```

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

* APISIX
* API7 Gateway

```
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: cas-auth-doc-service

    labels:

      docs-example: cas-auth

    routes:

      - name: cas-auth-doc-route

        hosts:

          - cas-auth-doc.local

        uris:

          - /*

        methods:

          - GET

          - POST

        plugins:

          cas-auth:

            idp_uri: http://cas-auth-doc-idp:18082/cas

            cas_callback_uri: http://cas-auth-doc.local:9080/cas/callback

            logout_uri: /cas/logout

            cookie:

              secret: replace-with-a-random-secret-at-least-32-characters

              secure: false

    upstream:

      type: roundrobin

      pass_host: node

      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=cas-auth
```

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

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

* Gateway API
* APISIX CRD

cas-auth-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: cas-auth-doc-route

spec:

  plugins:

    - name: cas-auth

      config:

        idp_uri: http://cas-auth-doc-idp:18082/cas

        cas_callback_uri: http://cas-auth-doc.local:9080/cas/callback

        logout_uri: /cas/logout

        cookie:

          secret: replace-with-a-random-secret-at-least-32-characters

          secure: false

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: cas-auth-doc-route

spec:

  parentRefs:

    - name: apisix

  hostnames:

    - cas-auth-doc.local

  rules:

    - matches:

        - path:

            type: PathPrefix

            value: /

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: cas-auth-doc-route

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

cas-auth-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/v2

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: cas-auth-doc-route

spec:

  ingressClassName: apisix

  plugins:

    - name: cas-auth

      enable: true

      config:

        idp_uri: http://cas-auth-doc-idp:18082/cas

        cas_callback_uri: http://cas-auth-doc.local:9080/cas/callback

        logout_uri: /cas/logout

        cookie:

          secret: replace-with-a-random-secret-at-least-32-characters

          secure: false

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: cas-auth-doc-route

spec:

  ingressClassName: apisix

  http:

    - name: cas-auth-doc-route

      match:

        hosts:

          - cas-auth-doc.local

        paths:

          - /*

        methods:

          - GET

          - POST

      backends:

        - serviceName: httpbin-external-domain

          servicePort: 80

      plugin_config_name: cas-auth-doc-route
```

Apply the route configuration:

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

The fixed cookie secret and disabled secure-cookie setting are only for local HTTP testing. In production, use a cryptographically random secret, HTTPS endpoints, and secure cookies.

Request a protected path and save the signed initiation cookie:

```
curl "http://127.0.0.1:9080/anything/order/123" \

  -H "Host: cas-auth-doc.local" \

  --silent \

  --dump-header login-headers.txt \

  --cookie-jar cas-cookies.txt \

  --output /dev/null



grep -Ei "^(HTTP/|Location:)" login-headers.txt
```

The gateway redirects the unauthenticated request to the CAS login endpoint:

```
HTTP/1.1 302 Moved Temporarily

Location: http://cas-auth-doc-idp:18082/cas/login?service=http%3A%2F%2Fcas-auth-doc.local%3A9080%2Fcas%2Fcallback
```

Simulate the identity provider returning the accepted ticket. The cookie jar supplies the signed initiation state from the first request:

```
curl "http://127.0.0.1:9080/cas/callback?ticket=ST-docs-alice" \

  -H "Host: cas-auth-doc.local" \

  --silent \

  --dump-header callback-headers.txt \

  --cookie cas-cookies.txt \

  --cookie-jar cas-cookies.txt \

  --output /dev/null



grep -Ei "^(HTTP/|Location:)" callback-headers.txt
```

After the gateway validates the ticket, it redirects to the original path:

```
HTTP/1.1 302 Moved Temporarily

Location: /anything/order/123
```

Send the original request with the authenticated session cookie:

```
curl "http://127.0.0.1:9080/anything/order/123" \

  -H "Host: cas-auth-doc.local" \

  --cookie cas-cookies.txt \

  --silent \

  --output /dev/null \

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

The authenticated request reaches the upstream:

```
Authenticated response: 200
```

### Log Out the CAS Session[​](#log-out-the-cas-session "Direct link to Log Out the CAS Session")

Request the configured logout path with the authenticated session cookie:

```
curl "http://127.0.0.1:9080/cas/logout" \

  -H "Host: cas-auth-doc.local" \

  --silent \

  --dump-header logout-headers.txt \

  --cookie cas-cookies.txt \

  --cookie-jar cas-cookies.txt \

  --output /dev/null



grep -Ei "^(HTTP/|Location:)" logout-headers.txt
```

The gateway deletes its session and redirects to the identity provider's logout endpoint:

```
HTTP/1.1 302 Moved Temporarily

Location: http://cas-auth-doc-idp:18082/cas/logout
```

Request the protected path again with the updated cookie jar:

```
curl "http://127.0.0.1:9080/anything/order/123" \

  -H "Host: cas-auth-doc.local" \

  --silent \

  --dump-header after-logout-headers.txt \

  --cookie cas-cookies.txt \

  --output /dev/null



grep -Ei "^(HTTP/|Location:)" after-logout-headers.txt
```

The missing session starts a new login flow:

```
HTTP/1.1 302 Moved Temporarily

Location: http://cas-auth-doc-idp:18082/cas/login?service=http%3A%2F%2Fcas-auth-doc.local%3A9080%2Fcas%2Fcallback
```

## Connect a Production CAS Provider[​](#connect-a-production-cas-provider "Direct link to Connect a Production CAS Provider")

CAS administration differs by provider, but the gateway integration requires the same values:

| Requirement                   | Provider and gateway configuration                                                                                                                                                             |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| CAS service                   | Register the public callback URL as an allowed CAS service. Configure the same absolute URL in `cas_callback_uri`.                                                                             |
| CAS endpoints                 | Set `idp_uri` to the provider base URL that exposes the CAS 2.0 login, service-validation, and logout endpoints.                                                                               |
| Transport and cookie security | Use HTTPS for the provider and callback, keep secure cookies enabled, and use a high-entropy cookie secret of at least 32 characters.                                                          |
| Session routing               | Keep a user's requests on the gateway instance that created the session, or run one instance for the protected route.                                                                          |
| Single logout                 | If enabled at the provider, send CAS single-logout POST requests to the configured callback URL. The gateway deletes the matching session and returns success without contacting the upstream. |

Session records are not replicated. They expire after one hour of inactivity and may be evicted earlier if the shared dictionary fills.

Handling single logout callbacks without contacting the upstream was introduced in API7 Enterprise 3.9.16 and 3.10.2, and in APISIX 3.21.0.
