跳到主要内容

dingtalk-auth

dingtalk-auth 插件基于钉钉开放平台的 OAuth 2.0 协议实现身份认证,通过验证请求中的钉钉授权码(code)获取用户信息,并将用户信息注入请求头或上下文,同时支持会话缓存避免重复认证,对接钉钉企业内部应用的访问控制。

插件时序流程

使用示例

前提条件

  1. 钉钉开放平台创建企业内部应用,获取 app_keyapp_secret
  2. 配置应用的授权回调地址,确保 redirect_uri 属于钉钉应用的可信域名;
  3. 确保网关能访问钉钉开放平台的 HTTPS 接口(api.dingtalk.comoapi.dingtalk.com)。

在路由上配置钉钉认证插件

以下示例演示如何在路由上实现钉钉认证。

创建路由并启用 dingtalk-auth 插件,具体插件配置如下:

curl "http://127.0.0.1:9180/apisix/admin/routes/dingtalk-auth-route" -X PUT -d '
{
"uri": "/get",
"plugins": {
"dingtalk-auth": {
"app_key": "dingxxxxxx",
"app_secret": "xxxxxx",
"secret": "session-secret-12345678",
"redirect_uri": "https://login.dingtalk.com/oauth2/auth?appid=dingxxxxxx&response_type=code&scope=openid&redirect_uri=https%3A%2F%2Fyour-domain.com%2Fcallback",
"cookie_expires_in": 86400,
"set_userinfo_header": true
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'

❶ Replace with your app key.

❷ Replace with your app secret.

❸ Replace with your secret, which should be a random string.

❹ Replace with your redirect URI registered with Dingtalk for OAuth callback.

  1. 首次请求(无 code): 在访问 http://127.0.0.1:9080/get时,响应状态码为 302 Found,响应头 Location 指向配置的 redirect_uri(钉钉授权页)。

  2. 携带 code 请求

    为了便于测试,这里可以通过 JSAPI Explorer 获取授权码,在实际的生产环境中,用户会在浏览器中完成钉钉授权流程后自动获得授权码。

    从钉钉授权页获取 code 后,携带 code 发起请求:http://127.0.0.1:9080/get?code=xxxx,验证成功时,响应包含会话 Cookie dingtalk_session,状态码为 200,上游服务可读取 X-Userinfo 头获取用户信息。

  3. 会话缓存验证: 携带会话 Cookie 发起请求 http://127.0.0.1:9080/get,此时网关验证 Cookie 中的用户信息,并注入 X-Userinfo 头转发到上游服务。

解码用户信息

当用户身份验证成功后,插件会在请求中添加包含 base64 编码的用户信息的头部 X-Userinfo

上游服务可解码 X-Userinfo 头获取用户信息:

import base64
import json

# 示例:Python解码X-Userinfo
userinfo_header = "eyJ1c2VyaWQiOiJkaW50YWxsaW5lLXVzZXJpZCJ9"
userinfo = json.loads(base64.b64decode(userinfo_header).decode('utf-8'))
print(userinfo) # 输出:{"userid": "dingtalk-userid"}