dingtalk-auth
dingtalk-auth 插件基于钉钉开放平台的 OAuth 2.0 协议实现身份认证,通过验证请求中的钉钉授权码(code)获取用户信息,并将用户信息注入请求头或上下文,同时支持会话缓存避免重复认证,对接钉钉企业内部应用的访问控制。
插件时序流程
使用示例
前提条件
- 在钉钉开放平台创建企业内部应用,获取
app_key和app_secret; - 配置应用的授权回调地址,确保
redirect_uri属于钉钉应用的可信域名; - 确保网关能访问钉钉开放平台的 HTTPS 接口(
api.dingtalk.com、oapi.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.
-
首次请求(无 code): 在访问
http://127.0.0.1:9080/get时,响应状态码为302 Found,响应头Location指向配置的redirect_uri(钉钉授权页)。 -
携带 code 请求:
为了便于测试,这里可以通过 JSAPI Explorer 获取授权码,在实际的生产环境中,用户会在浏览器中完成钉钉授权流程后自动获得授权码。
从钉钉授权页获取
code后,携带 code 发起请求:http://127.0.0.1:9080/get?code=xxxx,验证成功时,响应包含会话 Cookiedingtalk_session,状态码为 200,上游服务可读取X-Userinfo头获取用户信息。 -
会话缓存验证: 携带会话 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"}