# CAS Auth

`cas-auth` 插件使网关成为 CAS 2.0 服务提供方。它将未通过身份认证的用户重定向到 CAS 身份提供商，验证返回的服务票据，并在将原始请求发送到上游前创建会话。该插件还支持服务提供方发起的登出和 CAS 单点登出回调。

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

以下示例使用一个小型本地 CAS 服务，通过一个可接受的测试票据对会话进行身份认证，并验证服务提供方发起的登出。

### 启动模拟 CAS 服务器[​](#start-a-mock-cas-server "启动模拟 CAS 服务器的直接链接")

选择模拟 CAS 服务的运行环境。

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

```
mkdir cas-auth-example

cd cas-auth-example
```

创建模拟 CAS 服务：

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

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

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

启动模拟身份提供商：

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

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

根据模拟 CAS 脚本创建 ConfigMap：

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

  -n aic \

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

  --dry-run=client \

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

部署模拟身份提供商：

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

应用身份提供商配置：

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

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

本地示例中的固定票据仅用于测试。

### 对 CAS 会话进行身份认证[​](#authenticate-a-cas-session "对 CAS 会话进行身份认证的直接链接")

配置受保护的路由，使其回调路径和登出路径均由同一路由匹配。使用绝对回调 URL，可使 CAS 服务 URL 不依赖传入的 Host 请求头。

* Admin API
* ADC
* Ingress Controller

创建路由：

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

      }

    }

  }'
```

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

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

创建服务和路由：

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

预览变更，确认它们只影响本示例的资源：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

检查 `diff.yaml`，然后同步带有该标签的服务：

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

应用路由配置：

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

固定的 Cookie 密钥和禁用安全 Cookie 的设置仅用于本地 HTTP 测试。生产环境中请使用密码学安全的随机密钥、HTTPS 端点和安全 Cookie。

请求受保护的路径，并保存带签名的身份认证初始状态 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
```

网关会将未通过身份认证的请求重定向到 CAS 登录端点：

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

模拟身份提供商返回可接受的票据。Cookie 文件会提供首次请求中带签名的身份认证初始状态：

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

网关验证票据后，会重定向到原始路径：

```
HTTP/1.1 302 Moved Temporarily

Location: /anything/order/123
```

携带已通过身份认证的会话 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"
```

通过身份认证的请求会到达上游：

```
Authenticated response: 200
```

### 登出 CAS 会话[​](#log-out-the-cas-session "登出 CAS 会话的直接链接")

携带已通过身份认证的会话 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
```

网关会删除其会话，并重定向到身份提供商的登出端点：

```
HTTP/1.1 302 Moved Temporarily

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

使用更新后的 Cookie 文件再次请求受保护的路径：

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

会话缺失时会启动新的登录流程：

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

## 连接生产环境的 CAS 提供商[​](#connect-a-production-cas-provider "连接生产环境的 CAS 提供商的直接链接")

不同提供商的 CAS 管理方式有所不同，但网关集成所需的值相同：

| 要求               | 提供商和网关配置                                                                                                    |
| ------------------ | ------------------------------------------------------------------------------------------------------------------- |
| CAS 服务           | 将公网回调 URL 注册为允许的 CAS 服务，并在 `cas_callback_uri` 中配置相同的绝对 URL。                                |
| CAS 端点           | 将 `idp_uri` 设置为提供商的基础 URL，该地址应提供 CAS 2.0 登录、服务验证和登出端点。                                |
| 传输和 Cookie 安全 | 提供商和回调均使用 HTTPS，保持启用安全 Cookie，并使用至少 32 个字符的高熵 Cookie 密钥。                             |
| 会话路由           | 将用户的请求保持在创建该会话的网关实例上，或仅为受保护的路由运行一个实例。                                          |
| 单点登出           | 若提供商启用了此功能，请将 CAS 单点登出 POST 请求发送到配置的回调 URL。网关会删除匹配的会话并返回成功，不联系上游。 |

会话记录不会复制。会话在一小时无活动后过期；共享字典满时，会话还可能提前被逐出。

不联系上游而直接处理单点登出回调的功能自 API7 企业版 3.9.16、3.10.2 以及 APISIX 3.21.0 起支持。
