# LDAP Auth

`ldap-auth` 插件通过 LDAP 目录验证 HTTP Basic 凭据，并将通过身份认证的目录用户映射到[消费者](https://docs.apiseven.com/apisix/key-concepts/consumers.md)。消费者身份使面向消费者的插件、限流和分析功能能够在认证后生效。

此插件最适合用户专有名称遵循可预测模式的目录。对于嵌套目录结构或无法根据用户名构造专有名称的情况，请使用 [LDAP Auth Advanced](https://docs.apiseven.com/hub/ldap-auth-advanced.md)。

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

以下示例展示如何认证目录用户并将其映射到消费者，然后阻止可重复使用的目录密码传递给上游。

### 设置 OpenLDAP 和测试上游[​](#set-up-openldap-and-a-test-upstream "设置 OpenLDAP 和测试上游的直接链接")

为隔离的 OpenLDAP 目录选择环境，并设置上游以报告是否收到凭据请求头和消费者身份。

警告

此测试环境仅供本地评估，使用明文 LDAP。生产环境中，请通过 `use_tls: true` 使用 LDAPS、启用 `tls_verify`，并配置每个网关实例信任目录证书的签发 CA。

创建并进入工作目录：

```
mkdir ldap-auth-example

cd ldap-auth-example
```

创建目录引导数据：

ldap-users.ldif

```
dn: ou=users,dc=example,dc=org

objectClass: organizationalUnit

ou: users



dn: uid=johndoe,ou=users,dc=example,dc=org

objectClass: inetOrgPerson

cn: John Doe

sn: Doe

uid: johndoe

mail: johndoe@example.org

userPassword: john-secret
```

创建测试上游：

ldap-upstream.py

```
import json

from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer





class Handler(BaseHTTPRequestHandler):

    protocol_version = "HTTP/1.1"



    def do_GET(self):

        if self.path != "/ldap-check":

            self.send_error(404)

            return



        body = json.dumps({

            "authorization": "present" if self.headers.get("Authorization") else "absent",

            "consumer": self.headers.get("X-Consumer-Username", ""),

        }).encode() + b"\n"



        self.send_response(200)

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

        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", 8000), Handler).serve_forever()
```

* Docker
* Kubernetes

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

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



docker network create gateway-ldap-auth-net

docker network connect gateway-ldap-auth-net "$GATEWAY_CONTAINER"
```

启动包含测试用户的 OpenLDAP：

```
docker run -d \

  --name ldap-auth-openldap \

  --hostname ldap-auth-openldap \

  --network gateway-ldap-auth-net \

  -e LDAP_DOMAIN=example.org \

  -e LDAP_BASE_DN=dc=example,dc=org \

  -e 'LDAP_ORGANISATION=Example Organization' \

  -e LDAP_ADMIN_PASSWORD=admin-secret \

  -e LDAP_CREATE_PEOPLE_OU=false \

  -e LDAP_CREATE_GROUPS_OU=false \

  -v "$PWD/ldap-users.ldif:/docker-entrypoint-initdb.d/20-users.ldif:ro" \

  chrroessner/openldap:2.6.15-debian13.7
```

等待容器健康就绪，然后验证测试条目：

```
for attempt in $(seq 1 30); do

  if [ "$(docker inspect --format '{{.State.Health.Status}}' ldap-auth-openldap)" = "healthy" ]; then

    break

  fi

  sleep 1

done



test "$(docker inspect --format '{{.State.Health.Status}}' ldap-auth-openldap)" = "healthy"

docker inspect --format '{{.State.Health.Status}}' ldap-auth-openldap



docker exec ldap-auth-openldap ldapsearch -LLL -x \

  -H ldap://127.0.0.1:389 \

  -D 'cn=admin,dc=example,dc=org' \

  -w admin-secret \

  -b 'ou=users,dc=example,dc=org' \

  '(uid=johndoe)' dn uid
```

目录就绪并返回测试用户的 DN：

```
healthy

dn: uid=johndoe,ou=users,dc=example,dc=org

uid: johndoe
```

启动测试上游：

```
docker run -d \

  --name ldap-auth-upstream \

  --network gateway-ldap-auth-net \

  -v "$PWD/ldap-upstream.py:/ldap-upstream.py:ro" \

  python:3.13.15-alpine3.24 \

  python -u /ldap-upstream.py
```

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

根据目录数据和上游脚本创建 ConfigMap：

```
kubectl create configmap ldap-auth-users -n aic \

  --from-file=20-users.ldif=ldap-users.ldif \

  --dry-run=client -o yaml | kubectl apply -f -



kubectl create configmap ldap-auth-upstream-script -n aic \

  --from-file=ldap-upstream.py \

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

部署 OpenLDAP 和检查上游：

ldap-auth-upstreams.yaml

```
apiVersion: apps/v1

kind: Deployment

metadata:

  namespace: aic

  name: ldap-auth-openldap

spec:

  replicas: 1

  selector:

    matchLabels:

      app: ldap-auth-openldap

  template:

    metadata:

      labels:

        app: ldap-auth-openldap

    spec:

      containers:

        - name: ldap

          image: chrroessner/openldap:2.6.15-debian13.7

          env:

            - name: LDAP_DOMAIN

              value: example.org

            - name: LDAP_BASE_DN

              value: dc=example,dc=org

            - name: LDAP_ORGANISATION

              value: Example Organization

            - name: LDAP_ADMIN_PASSWORD

              value: admin-secret

            - name: LDAP_CREATE_PEOPLE_OU

              value: "false"

            - name: LDAP_CREATE_GROUPS_OU

              value: "false"

          ports:

            - containerPort: 389

          volumeMounts:

            - name: users

              mountPath: /docker-entrypoint-initdb.d/20-users.ldif

              subPath: 20-users.ldif

              readOnly: true

          readinessProbe:

            tcpSocket:

              port: 389

      volumes:

        - name: users

          configMap:

            name: ldap-auth-users

---

apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: ldap-auth-openldap

spec:

  selector:

    app: ldap-auth-openldap

  ports:

    - port: 389

      targetPort: 389

---

apiVersion: apps/v1

kind: Deployment

metadata:

  namespace: aic

  name: ldap-auth-upstream

spec:

  replicas: 1

  selector:

    matchLabels:

      app: ldap-auth-upstream

  template:

    metadata:

      labels:

        app: ldap-auth-upstream

    spec:

      containers:

        - name: upstream

          image: python:3.13.15-alpine3.24

          command: ["python", "-u", "/app/ldap-upstream.py"]

          ports:

            - containerPort: 8000

          volumeMounts:

            - name: script

              mountPath: /app/ldap-upstream.py

              subPath: ldap-upstream.py

              readOnly: true

      volumes:

        - name: script

          configMap:

            name: ldap-auth-upstream-script

---

apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: ldap-auth-upstream

spec:

  selector:

    app: ldap-auth-upstream

  ports:

    - port: 8000

      targetPort: 8000
```

应用上游配置：

```
kubectl apply -f ldap-auth-upstreams.yaml

kubectl rollout status -n aic deployment/ldap-auth-openldap

kubectl rollout status -n aic deployment/ldap-auth-upstream
```

### 认证并映射目录用户[​](#authenticate-and-map-a-directory-user "认证并映射目录用户的直接链接")

为 LDAP 条目创建消费者并保护上游路由。

* Admin API
* ADC
* Ingress Controller

创建消费者：

```
curl "http://127.0.0.1:9180/apisix/admin/consumers/ldap-john" -X PUT \

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

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

  -d '{

    "username": "ldap-john",

    "plugins": {

      "ldap-auth": {

        "user_dn": "uid=johndoe,ou=users,dc=example,dc=org"

      }

    }

  }'
```

创建路由：

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

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

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

  -d '{

    "uri": "/ldap-check",

    "plugins": {

      "ldap-auth": {

        "ldap_uri": "ldap-auth-openldap:389",

        "base_dn": "ou=users,dc=example,dc=org",

        "uid": "uid"

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "ldap-auth-upstream:8000": 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

```
consumers:

  - username: ldap-john

    labels:

      docs-example: ldap-auth

    plugins:

      ldap-auth:

        user_dn: uid=johndoe,ou=users,dc=example,dc=org

services:

  - name: ldap-auth-service

    labels:

      docs-example: ldap-auth

    routes:

      - name: ldap-auth-route

        uris:

          - /ldap-check

        plugins:

          ldap-auth:

            ldap_uri: ldap-auth-openldap:389

            base_dn: ou=users,dc=example,dc=org

            uid: uid

    upstream:

      type: roundrobin

      nodes:

        - host: ldap-auth-upstream

          port: 8000

          weight: 1
```

预览带标签的资源，确认差异中没有非预期的更改或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --include-resource-type consumer \

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

同步已审阅的资源：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --include-resource-type consumer \

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

* Gateway API
* APISIX CRD

不支持消费者凭据

Gateway API 的 `Consumer` 资源未暴露 LDAP Auth 凭据。此插件请使用 APISIX CRD 方式。

ldap-auth-ic.yaml

```
apiVersion: v1

kind: Secret

metadata:

  namespace: aic

  name: ldap-john

type: Opaque

stringData:

  user_dn: uid=johndoe,ou=users,dc=example,dc=org

---

apiVersion: apisix.apache.org/v2

kind: ApisixConsumer

metadata:

  namespace: aic

  name: ldap-john

spec:

  ingressClassName: apisix

  authParameter:

    ldapAuth:

      secretRef:

        name: ldap-john

---

apiVersion: apisix.apache.org/v2

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: ldap-auth-route

spec:

  ingressClassName: apisix

  plugins:

    - name: ldap-auth

      enable: true

      config:

        ldap_uri: ldap-auth-openldap:389

        base_dn: ou=users,dc=example,dc=org

        uid: uid

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: ldap-auth-route

spec:

  ingressClassName: apisix

  http:

    - name: ldap-auth-route

      match:

        paths:

          - /ldap-check

      backends:

        - serviceName: ldap-auth-upstream

          servicePort: 8000

      plugin_config_name: ldap-auth-route
```

应用配置：

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

发送不含凭据的请求：

```
curl --include "http://127.0.0.1:9080/ldap-check"
```

插件向客户端发起质询，并在请求到达上游前予以拒绝：

```
HTTP/1.1 401 Unauthorized

WWW-Authenticate: Basic realm="ldap"

...

{"message":"Missing authorization in request"}
```

使用正确的用户名和错误的密码发送请求：

```
curl --include "http://127.0.0.1:9080/ldap-check" \

  --user johndoe:wrong-secret
```

目录拒绝绑定：

```
HTTP/1.1 401 Unauthorized

WWW-Authenticate: Basic realm="ldap"

...

{"message":"Invalid user authorization"}
```

发送有效的目录凭据：

```
curl "http://127.0.0.1:9080/ldap-check" \

  --user johndoe:john-secret
```

请求携带匹配的消费者身份到达上游。Admin API 和 ADC 流程使用配置的消费者名称，默认配置还会转发凭据请求头：

```
{"authorization": "present", "consumer": "ldap-john"}
```

Ingress Controller 根据资源命名空间和名称派生消费者用户名。对于上例中的 `aic` 命名空间和 `ldap-john` 资源，响应包含：

```
{"authorization": "present", "consumer": "aic_ldap-john"}
```

### 停止转发目录凭据[​](#stop-forwarding-directory-credentials "停止转发目录凭据的直接链接")

HTTP Basic 请求头包含目录密码，该密码通常可在此 API 之外重复使用。移除凭据的功能从 API7 Gateway 3.10.6 和 APISIX 3.18.0 开始提供。API7 Gateway 3.9 不支持此选项。

* Admin API
* ADC
* Ingress Controller

替换现有路由上的插件配置：

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

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

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

  -d '{

    "ldap_uri": "ldap-auth-openldap:389",

    "base_dn": "ou=users,dc=example,dc=org",

    "uid": "uid",

    "hide_credentials": true

  }'
```

在 `adc.yaml` 中，为现有路由启用凭据移除：

adc.yaml（路由插件）

```
plugins:

  ldap-auth:

    ldap_uri: ldap-auth-openldap:389

    base_dn: ou=users,dc=example,dc=org

    uid: uid

    hide_credentials: true
```

预览更新后的服务：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

同步已审阅的服务：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

* Gateway API
* APISIX CRD

不支持消费者凭据

Gateway API 的 `Consumer` 资源未暴露 LDAP Auth 凭据。此插件请使用 APISIX CRD 方式。

ldap-auth-ic.yaml

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

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: ldap-auth-route

spec:

  ingressClassName: apisix

  plugins:

    - name: ldap-auth

      enable: true

      config:

        ldap_uri: ldap-auth-openldap:389

        base_dn: ou=users,dc=example,dc=org

        uid: uid

        hide_credentials: true
```

应用更新后的插件配置：

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

再次发送有效凭据：

```
curl "http://127.0.0.1:9080/ldap-check" \

  --user johndoe:john-secret
```

消费者仍然关联，但上游不再收到凭据请求头。Admin API 和 ADC 流程返回：

```
{"authorization": "absent", "consumer": "ldap-john"}
```

Ingress Controller 流程返回派生的消费者用户名：

```
{"authorization": "absent", "consumer": "aic_ldap-john"}
```

## 何时使用 LDAP Auth Advanced[​](#when-to-use-ldap-auth-advanced "何时使用 LDAP Auth Advanced的直接链接")

LDAP Auth 根据配置的用户属性、客户端提供的用户名和基础 DN 直接构造用户专有名称。LDAP Auth Advanced 则通过搜索目录解析用户专有名称，并且可以在不映射消费者的情况下进行认证。该插件适用于 API7 Gateway 3.10.5 及更高版本和 APISIX 3.18.0 及更高版本。

## 限制[​](#limitations "限制的直接链接")

凭据缺失或格式错误、目录连接失败、绑定被拒绝以及消费者映射缺失都会返回 `401 Unauthorized`。

插件会移除解码后的用户名和密码中的空白字符；包含冒号的密码会在第一段之后被截断。

DN 转义从 API7 Gateway 3.10.6 和 APISIX 3.18.0 开始提供。API7 Gateway 3.9 不会转义用户名中的结构字符。在该版本中，请使用不含这些字符的目录用户名。
