Files
chongming-plugins/auth_oauth/README.md
T

62 lines
3.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Auth OAuth 插件 — 第三方授权登录示例(身份源插件)
基于 `chongming-auth` 共享契约实现**身份源插件**的参考实现:准入判断归插件,
平台凭证签发归 `chongming_auth.issue_token`(claims 契约与网关内置登录完全一致)。
第三方身份登录后拿到的 token 与内置登录**完全等价**——网关 JWT 验签、
`user_info` 随信封透传、admin API 判超管全部无缝生效。
## 提供的身份源
| 身份源 | 模式 | 端点 |
| --- | --- | --- |
| GitHub | OAuth2 授权码(SPA JSON 流程) | `GET /auth/oauth/github_authorize`、`POST /auth/oauth/github_callback` |
| 手机号 | 一次性验证码(演示模式) | `POST /auth/oauth/phone_send_code`、`POST /auth/oauth/phone_login` |
## 身份源插件的标准形态(写新身份源时照此扩展)
1. **准入**:校验第三方凭据(OAuth code / OTP / LDAP 密码 / ...);
2. **映射**:在插件自有绑定表 `identity_bindings(provider, provider_uid, user_id)`
中 find-or-create——老用户换身份源登录仍是同一账号体系;
3. **建号**:无绑定时新建 `users` 账号(密码为随机不可用值)+ 绑定记录,
与网关内置登录**共用同一张 users 表**(`chongming_auth.open_database`);
4. **签发**:`chongming_auth.issue_token(user, secret, algorithm)`。
扩展新身份源(LDAP / 企业微信 / 飞书 / OIDC ...)只需:加一个 provider 对接模块
+ 一组 TOML 路由 + 一个 `@rpc_method` 端点,调 `store.find_or_create_user` 即可。
## 配置
`config/workers/auth_oauth/config.toml` 的 `[workers.config]`:
```toml
return_otp_in_response = true # 演示模式:验证码随响应返回。生产必须 false 并接短信通道
[workers.config.github]
client_id / client_secret / redirect_uri / scope
```
## 安全说明(务必阅读)
- **本插件须以 inline 模式运行**(默认):`issue_token` 需要 `[security]` 签名密钥,
external 进程持有该密钥即能铸造超管 token。external 化前需平台提供内部签发 API
或按 issuer 分离密钥。
- `return_otp_in_response` 仅限本地演示,生产必须关闭并接真实短信通道。
- OAuth state 与 OTP 验证码均存共享缓存(`chongming_cache`),一次性消费、300s 过期。
## 踩坑记录(写插件必读)
**插件必须提供 `models/pydantic.py`**(gen_models 产物位置,手写等价物亦可)。
网关契约校验按 `plugins.<type>.models.pydantic` → `src.plugins....` → `workers....`
顺序探测;缺失时 `src.plugins.` 兜底路径会以第二个模块名重新执行整个插件包
(父包导入链),插件内自定义 SQLModel 表会在全局元数据中重复定义,
网关启动即崩(`Table 'xxx' is already defined for this MetaData instance`)。
## 依赖
| 工具包 | 用途 |
| --- | --- |
| `chongming-auth` | Users 模型 / 建库 / 登录校验 / issue_token(共享契约) |
| `chongming-cache` | OAuth state 与 OTP 验证码存储 |
| `chongming-worker` | `@rpc_method` 装饰器 + Worker 运行时 |
| `httpx` | GitHub OAuth API 调用 |