2,285 字约 7 分钟
GitHub 第三方登录集成笔记
BFF 模式下 GitHub 登录的完整实现:PKCE、State Cookie、双流程与错误码映射。
基于本项目
server/app/现有实现整理。完整覆盖 BFF 模式、PKCE、State Cookie、双流程(login/bind)、弹窗(popup)/整页(page)双落地方式、错误码映射、Cookie 会话。
一、整体架构:为什么用 BFF 模式
本项目 GitHub 登录采用 BFF(Backend-For-Frontend)模式,而不是常见的纯前端直跳模式:
浏览器 后端 FastAPI GitHub
│ │ │
│── /start ─────→│ │
│ │── 302 GitHub ──────→│
│ │←── 302 callback ────│
│ │ (code+state) │
│ │── POST /token ─────→│
│ │←── access_token ────│
│ │── GET /user ───────→│
│ │←── user info ───────│
│←── 302 success ─│ │
│ (session │ │
│ cookie) │ │
核心原则:浏览器只跟自己的后端交互,永远不接触 GitHub 的 client_secret。
| 优势 | 说明 |
|---|---|
| 凭证隔离 | GITHUB_CLIENT_SECRET 只在后端内存,浏览器永远拿不到 |
| 流程可控 | 错误一律 redirect 到前端错误落地页(/auth/error 或 /oauth-popup.html),而不是把 GitHub 的错误码直接抛给浏览器 |
| 可扩展 | auth_methods 表 + Authlib 注册结构,扩展 Google / 微信只需加 oauth.register(...) |
| 双语义复用 | 同一套 GitHub OAuth 代码既支持「登录」也支持「绑定」 |
二、关键设计选型
1. Authlib 而非手撸 OAuth
app/services/auth/oauth.py:34 使用 authlib.integrations.starlette_client.OAuth:
oauth = OAuth()
if env_settings.GITHUB_CLIENT_ID and env_settings.GITHUB_CLIENT_SECRET:
oauth.register(
name="github",
client_id=env_settings.GITHUB_CLIENT_ID,
client_secret=env_settings.GITHUB_CLIENT_SECRET,
access_token_url=env_settings.GITHUB_ACCESS_TOKEN_URL,
authorize_url="https://github.com/login/oauth/authorize",
api_base_url="https://api.github.com/",
client_kwargs={"scope": "read:user user:email"},
)
理由:
- RFC 6749 / 7636(PKCE)规范由库保证
- GitHub 不返回标准 JSON 而是
application/x-www-form-urlencoded,Authlib 帮处理 - 支持
fetch_access_token(token, code, code_verifier)自动带 verifier
2. 启用 PKCE(S256)
app/services/auth/__init__.py:159:
def generate_pkce_pair() -> tuple[str, str]:
verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode()
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
return verifier, challenge
虽然 GitHub 对 public client 不强制 PKCE,但启用后:
- 即使授权码被截获,没有
code_verifier也换不出 token - 给将来切 SPA + public client 留余地
3. State 作为 CSRF Token
oauth.py:195:
state = secrets.token_urlsafe(32) # 纯 random
state只用于"防 CSRF / 防 replay",不带业务语义(修复 Bug #1)- 业务流程(login / bind)通过独立的
flow参数或路由路径区分 - callback 时
hmac.compare_digest(cookie_state, query_state),等长比较防时序攻击
4. 双流程(Login + Bind)共用一套回调
GET /api/auth/github/login/start # 未登录入口
GET /api/auth/github/login/callback # 未登录用户回调
GET /api/auth/github/bind/start # 已登录用户在「账号绑定」页点 GitHub
GET /api/auth/github/bind/callback # 已登录用户回调
用 Flow 枚举 + 路由分离实现,避免在 state 里塞复合前缀(那是 Bug #1 的根因)。
5. 自动转 Bind 语义(Bug #3)
oauth.py:269 的关键逻辑:
if flow == Flow.LOGIN:
if current_user_id is not None:
# 已登录用户误点「使用 GitHub 登录」→ 自动当 bind 处理
if not await _bind_to_user(current_user_id, github_id):
return redirect_to_auth_error("already_bound_other", flow)
await _users_cud.update_last_login(current_user_id)
session_user_id = current_user_id
else:
user = await _login_or_create(...)
session_user_id = user.id
业务意义:「使用 GitHub 登录」按钮永远不应该创建新账号——它要么走 login(未登录),要么走 bind(已登录)。
6. 回调"全包 try/except"(Bug #4)
oauth.py:222:
async def svc_github_callback(...) -> RedirectResponse:
try:
return await _handle_github_callback(request, flow, current_user_id)
except Exception as e:
log.exception(...)
return redirect_to_auth_error("unknown", flow)
任何未处理异常都 redirect 到前端错误页,浏览器永远不会被留在 callback URL 上看不到反馈。
三、数据模型
app/models/models.py:
class User(Base):
"""用户主表 — 基础信息,登录凭证在 auth_methods"""
id: UUID
nickname: str
avatar: str | None
created_at / updated_at / last_login_at: datetime(timezone)
class AuthMethod(Base):
"""登录方式 — 邮箱/GitHub/未来扩展"""
id: UUID
user_id: UUID(FK → users.id, ON DELETE CASCADE)
auth_type: str # 'email' | 'github',CheckConstraint 限制
auth_id: str # email 地址 / GitHub numeric id
password_hash: str | None # 仅 email 用 bcrypt
verified: bool # email 需邮箱验证,GitHub 默认 True
关键设计:
users与auth_methods1:N 关系,每个用户可同时绑邮箱 + GitHubUniqueConstraint("auth_type", "auth_id")保证一个 GitHub 账号只能绑一个用户auth_type用CheckConstraint限定枚举值,DB 层兜底防脏数据
四、后端代码全景
app/
├── routers/auth.py # HTTP 入口,薄壳
├── schemas/auth.py # Pydantic v2 入参/出参
├── services/auth/
│ ├── __init__.py # Cookie 签发、PKCE、依赖注入
│ ├── email.py # 邮箱注册/登录/重置
│ ├── methods.py # 绑定/解绑/列表
│ └── oauth.py # GitHub OAuth 核心
├── crud/
│ ├── auth_methods.py # auth_methods 表 CRUD
│ └── users.py # users 表 CRUD + create_user_with_auth_method
├── models/models.py # User + AuthMethod ORM
├── middleware/session_refresh.py # 自动续签 session cookie
└── utils/
└── exception_handler.py # OAuthCallbackError 异常码
数据流:login 流程
1. 浏览器点「GitHub 登录」→ window.open('/api/auth/github/login/start?mode=popup&nonce=...')
(弹窗被拦截时回退整页 /api/auth/github/login/start)
2. 后端 svc_github_start:
- 生成 state + pkce pair
- github.create_authorization_url(redirect_uri, state, code_challenge, "S256")
- Set-Cookie: oauth_state, oauth_pkce, oauth_mode, oauth_nonce
(HttpOnly, Path=/api/auth, Max-Age=600)
- 302 → https://github.com/login/oauth/authorize?...
3. 用户在 GitHub 点 Authorize
4. GitHub 302 → /api/auth/github/login/callback?code=xxx&state=yyy
5. 后端 callback 分两条路径:
popup 首跳(没有 complete=1):
- 只读 oauth_mode / oauth_nonce
- 立即 302 → /oauth-popup.html?status=processing&code=...&state=...&nonce=...
- 不交换 token、不查 DB、不清理 cookie,避免弹窗白屏
popup 静态页随后 fetch 同一 callback?...&complete=1;page 模式直接执行:
a. 检测 query.error → 映射到错误码
b. hmac.compare_digest(cookie_state, query_state)
c. 读 oauth_pkce cookie
d. github.fetch_access_token(code, redirect_uri, code_verifier)
e. github.get("user", token=token) → {id, login, avatar_url}
f. _login_or_create / _bind_to_user
g. set_session_cookie + clear_oauth_cookies
h. popup 模式 → /oauth-popup.html?status=success|error&flow=login&nonce=...
page 模式 → /auth/success?flow=login 或 /auth/error?code=...
6. popup 页通过 postMessage / BroadcastChannel 通知主窗口;主窗口拉 /api/auth/me 刷新用户
page 模式仍由 /auth/success 拉 /api/auth/me 后 redirect 到主页
数据流:bind 流程
bind 与 login 代码 95% 相同,差异点:
| 差异点 | login | bind |
|---|---|---|
| 入口 | 不要求登录 | 未登录 → redirect 错误落地页(code=session_missing) |
| callback 当前用户 | 可空 | 必须存在,否则 session_missing |
| 已绑处理 | _login_or_create 自动复用 | _bind_to_user 检查是否被他人绑定 |
| 同一 GitHub 二次走 | 当作 bind 复用 | 幂等成功(同一用户) |
五、Cookie 与会话设计
会话与 OAuth 临时 Cookie
| Cookie 名 | 用途 | 有效期 | Path | 属性 |
|---|---|---|---|---|
session_token | 登录态(HMAC 签名 user_id.iat.sig) | 30 天 | / | HttpOnly, SameSite=Lax, Secure(可选) |
oauth_state | OAuth state(CSRF token) | 10 分钟 | /api/auth | HttpOnly |
oauth_pkce | PKCE verifier | 10 分钟 | /api/auth | HttpOnly |
oauth_mode | 落地方式(page / popup) | 10 分钟 | /api/auth | HttpOnly |
oauth_nonce | popup 与主窗口的消息关联 nonce | 10 分钟 | /api/auth | HttpOnly |
session_token 格式
app/services/auth/__init__.py:38:
def _sign(user_id: str, issued_at: int) -> str:
payload = f"{user_id}.{issued_at}"
sig = hmac.new(AUTH_SIGN_KEY.encode(), payload.encode(), "sha256").hexdigest()[:32]
return f"{payload}.{sig}"
格式:{uuid}.{unix_ts}.{hex_sig[:32]},三段以 . 分隔。
SessionRefreshMiddleware 自动续签
app/main.py 中的中间件读取 request.state.session_remaining(由 get_current_user 写入):
- 剩余 < 阈值(如 7 天)→ 自动重新签发新 cookie
- 浏览器无感刷新过期时间
Cookie 安全属性对照
response.set_cookie(
key="session_token",
value=token,
httponly=True, # 防 XSS 读取
samesite="lax", # 防 CSRF(GitHub 302 回跳需要 lax)
secure=env_settings.COOKIE_SECURE, # 生产 True,dev False(http://localhost)
domain=env_settings.COOKIE_DOMAIN or None, # 生产用 .example.com,子域共享
max_age=30 * 24 * 3600,
path="/",
)
六、错误码体系
后端 → 前端的契约
后端 callback 不返 JSON,始终 302 到前端错误落地页:
- page 模式:
/auth/error?code=XXX&flow=YYY,由pages/AuthError.tsx展示 - popup 模式:
/oauth-popup.html?status=error&code=XXX&flow=YYY&nonce=...,由静态弹窗页通知主窗口
错误码来源有两类:
| 类别 | 来源 | 例子 |
|---|---|---|
| GitHub RFC 6749 错误 | GitHub 回调 query error 参数 | access_denied, invalid_scope |
| 自检错误 | 业务逻辑抛 OAuthCallbackError(code=...) | invalid_state, token_exchange_failed, already_bound_other, session_missing, not_configured |
_OAUTH_ERROR_MAP 映射
app/services/auth/oauth.py:72:
_OAUTH_ERROR_MAP: dict[str, str] = {
"access_denied": "access_denied",
"invalid_request": "invalid_request",
"invalid_scope": "invalid_scope",
"unauthorized_client": "unauthorized_client",
"server_error": "github_server_error",
"temporarily_unavailable": "github_unavailable",
}
前端错误码 → 用户文案
front/src/constants/oauth.ts 集中维护 OAUTH_ERROR_MAP,每个 code 对应 { title, hint, retryable },由 page 错误页与 popup 通知共用。前端绝不展示后端 message 或 GitHub error_description,避免暴露内部信息。
七、环境变量
server/.env:
AUTH_SIGN_KEY=<random-32-bytes-hex> # session 签名密钥
GITHUB_CLIENT_ID=Iv1.xxx # GitHub OAuth App
GITHUB_CLIENT_SECRET=ghp_xxx # 仅后端持有
GITHUB_REDIRECT_URI=http://localhost:5173/api/auth/github/login/callback # 走前端同源代理
GITHUB_ACCESS_TOKEN_URL=https://github.com/login/oauth/access_token
FRONTEND_BASE_URL=http://localhost:5173 # 错误/成功页、popup 页跳转目标
COOKIE_SECURE=false # 生产 True
COOKIE_DOMAIN= # 生产 .example.com
GitHub OAuth App 设置:
- Homepage URL:
http://localhost:5173(dev)/https://app.example.com(prod) - Authorization callback URL: 必须与
GITHUB_REDIRECT_URI一字不差 - ❗ GitHub 不支持通配符 callback,本地/prod 需要建两个 OAuth App
同源要求(popup 模式):
postMessage/BroadcastChannel只在同源页面之间工作,FRONTEND_BASE_URL必须与浏览器地址栏完全一致(含端口)。例如用 Nginx 的8080访问时,需要把FRONTEND_BASE_URL和GITHUB_REDIRECT_URI都改为http://localhost:8080/...;否则弹窗只能完成登录,主窗口收不到通知。
八、前端集成
触发登录(LoginForm)
front/src/hooks/useGithubOAuth.ts:
// 必须在点击事件中同步调用,避免 window.open 被浏览器拦截
export function startGithubOAuth(flow: 'login' | 'bind'): void {
const nonce = createNonce()
const popup = window.open(`/api/auth/github/${flow}/start?mode=popup&nonce=${nonce}`, ...)
if (popup === null) {
window.location.href = `/api/auth/github/${flow}/start` // 弹窗被拦截 → 整页兜底
return
}
pendingOAuth = { nonce, flow, popup }
}
关键:主窗口不再整页跳转。GitHub 回调先 302 到静态 /oauth-popup.html?status=processing,弹窗立即显示暗色加载态;静态页再 fetch callback?...&complete=1 完成耗时的 token 交换,避免后端同步处理 2~3 秒时弹窗白屏。
完成后静态页会:
postMessage给window.opener(校验 target origin)- 同时通过
BroadcastChannel('github-oauth')广播(GitHub 设置 COOP 切断 opener 时仍可送达)
主窗口 useGithubOAuthListener() 校验 origin、消息结构、nonce、event.source 后,只请求 /api/auth/me 并更新 store;bind 流程额外失效 methods 缓存并打开设置页。
触发绑定(AccountBinding)
front/src/components/setting/personal/AccountBinding.tsx 复用 useBindGithub(),内部同样调用 startGithubOAuth('bind')。
错误落地页
front/src/pages/AuthError.tsx(page 模式兜底)继续提供「重新发起」:
const handleRetry = () => {
if (initial.flow === 'bind' && !isLoggedIn) {
navigate('/', { replace: true }) // bind 必须先登录
return
}
const target = initial.flow === 'bind'
? '/api/auth/github/bind/start'
: '/api/auth/github/login/start'
window.location.href = target
}
popup 模式的错误由主窗口 toast 展示,错误码 → 文案映射统一放在 front/src/constants/oauth.ts。
useAccountBinding Hook
封装查询已绑定方式、绑定邮箱、解绑、绑定 GitHub 等操作,通过 TanStack Query 走 authKeys(queryKeys.js 集中管理)。
九、绑定/解绑的业务约束
app/services/auth/methods.py:99:
async def svc_unbind(user_id: UUID, req: UnbindRequest):
methods = await _auth_crud.list_auth_methods(user_id)
if len(methods) <= 1:
raise ValidationError("至少需要保留一种登录方式")
...
强约束:
- 至少保留一种登录方式——避免用户把自己锁在外面
- GitHub 已被他人绑定 → 冲突(
already_bound_other) - GitHub 已绑当前用户 → 幂等成功(
_bind_to_user返回 True)
auth_type 在 Pydantic 层用 field_validator 限定 "email" | "github",DB 层用 CheckConstraint 兜底。
十、典型场景时序
以下时序以 page 模式为例;popup 模式仅把成功/错误落地页换成
/oauth-popup.html,再通知主窗口。
场景 A:首次 GitHub 登录(用户不存在)
浏览器 后端 GitHub DB
│ │ │ │
│── start ───────→│ │ │
│ │── 302 ──────────→│ │
│ │ │ │
│ │←── 302 callback ─│ │
│ │ (code+state) │ │
│ │ │ │
│ │── POST /token ──→│ │
│ │←── access_token ─│ │
│ │── GET /user ────→│ │
│ │←── user info ───│ │
│ │ │
│ │── INSERT users ─────────────────→│
│ │── INSERT auth_methods ─────────→│
│ │ (github, github_id) │
│ │ │
│←─ 302 success ──│ │
│ Set-Cookie │ │
│ session_token │ │
场景 B:已登录用户给当前账号绑 GitHub
浏览器 后端 GitHub DB
│ │ │ │
│── bind/start ──→│ │ │
│ (带 cookie │ │ │
│ session) │── 302 ──────────→│ │
│ │←── 302 callback ─│ │
│ │ (code+state) │ │
│ │── token+user ───→│ │
│ │←── user info ────│ │
│ │ │
│ │── 校验 session │
│ │── SELECT auth_methods │
│ │ WHERE github=X │
│ │ → None(未被他人绑) │
│ │── INSERT auth_methods ─────────→│
│ │ (github, github_id, user_id) │
│ │ │
│←─ 302 success ──│ │
场景 C:GitHub 已被他人绑定 → 冲突
...(同 B 的前 6 步)...
│ │── SELECT auth_methods │
│ │ WHERE github=X │
│ │ → 命中他人 user_id │
│ │ │
│←─ 302 /auth/error?code=already_bound_other ──────│
场景 D:用户取消授权
浏览器 后端 GitHub
│ │ │
│── start ───────→│ │
│ │── 302 ──────────→│
│ │ │
│ │←── 302 callback ─│
│ │ error=access_denied
│ │ │
│ │── _OAUTH_ERROR_MAP.get('access_denied')
│ │ → 'access_denied'
│ │ │
│←─ 302 /auth/error?code=access_denied ─│
│ │ │
十一、安全要点速查
| 风险 | 缓解措施 |
|---|---|
| client_secret 泄露 | BFF 模式,secret 只在后端内存 |
| CSRF / Replay | state 用 secrets.token_urlsafe(32),HMAC 等长比较 |
| 授权码截获 | PKCE S256,verifier 只存 HttpOnly cookie |
| XSS 读 cookie | HttpOnly + SameSite=Lax |
| 中间人 | 生产 COOKIE_SECURE=True(HTTPS only) |
| Session 篡改 | HMAC-SHA256 签名,签名失败返 401 |
| Session 永久化 | iat 写入签名,验签时强制 30 天过期 |
| 用户被锁住 | 解绑前校验 len(methods) > 1 |
| 误点登录创建新用户 | Bug #3 修复:login 流程自动转为 bind |
| 异常吞 callback | Bug #4 修复:全包 try/except → redirect 错误页 |
| 错误码泄露 | 前端只展示 constants/oauth.ts 内的静态文案 |
| popup 消息伪造 | 校验 event.origin、event.source、随机 nonce;消息不含 token,只传状态/错误码 |
| 弹窗被拦截 | window.open 返回 null 时回退整页 OAuth 流程 |
十二、扩展新 Provider(以 Google 为例)
照搬现有模式只需三步:
# 1. app/services/auth/oauth.py 注册
oauth.register(
name="google",
client_id=env_settings.GOOGLE_CLIENT_ID,
client_secret=env_settings.GOOGLE_CLIENT_SECRET,
access_token_url="https://oauth2.googleapis.com/token",
authorize_url="https://accounts.google.com/o/oauth2/v2/auth",
api_base_url="https://openidconnect.googleapis.com/v1/",
client_kwargs={"scope": "openid email profile"},
)
# 2. app/routers/auth.py 加 4 个路由
@router.get("/google/login/start") ...
@router.get("/google/login/callback") ...
@router.get("/google/bind/start") ...
@router.get("/google/bind/callback") ...
# 3. models/models.py 的 CheckConstraint 加 'google'
CheckConstraint("auth_type IN ('email','github','google')")
业务逻辑(_login_or_create / _bind_to_user)完全不用改——它们只认 auth_type 字符串。
十三、常见坑与修复历史
| Bug | 现象 | 修复 |
|---|---|---|
| #1 | state 带 flow 前缀(login:xxx),拆分逻辑出错 | state 改纯 random,flow 走路由/参数 |
| #2 | (早期)dev 用 http 但 cookie 强制 secure,callback 失败 | COOKIE_SECURE 由 env 控制,dev False |
| #3 | 已登录用户点「GitHub 登录」误建新账号 | login callback 检测到 current_user_id 自动转 bind |
| #4 | 异常时浏览器停在 callback URL 看不到反馈 | 全包 try/except,redirect 到错误页 |
| #5 | 登录成功但 callback 返回 500,日志 delete_cookie() got an unexpected keyword argument 'max_age' | clear_oauth_cookies 误传 max_age;拆分共有属性并加兜底 |
| #6 | 暗色模式下 GitHub 整页回跳时闪白 | 主流程改为 popup(主窗口不刷新);index.html 与 oauth-popup.html 内联首帧主题底色,page 兜底路径也不再白屏 |
| #7 | popup 在 GitHub 授权回调期间空白 2~3 秒 | 首跳只做 302 到静态加载页,静态页再 fetch complete=1 执行 token 交换;加载页始终显示暗色 spinner |
十四、关键文件索引
| 文件 | 作用 |
|---|---|
app/routers/auth.py | HTTP 入口(薄壳) |
app/services/auth/oauth.py | GitHub OAuth 核心(含 Authlib 注册 + PKCE + state 校验 + 双流程) |
app/services/auth/__init__.py | session cookie 签发/验证、PKCE 工具、依赖注入 |
app/services/auth/methods.py | 绑定/解绑/列表业务 |
app/services/auth/email.py | 邮箱注册/登录/重置 |
app/crud/auth_methods.py | auth_methods 表 CRUD |
app/crud/users.py | users 表 CRUD + create_user_with_auth_method |
app/models/models.py | User + AuthMethod ORM(含 CheckConstraint) |
app/schemas/auth.py | Pydantic v2 入参/出参 |
app/utils/exception_handler.py | OAuthCallbackError(code, message) |
app/config/env_setting.py | GITHUB_* / AUTH_SIGN_KEY / COOKIE_* 配置 |
front/src/hooks/useGithubOAuth.ts | popup 启动、主窗口消息监听(postMessage + BroadcastChannel) |
front/src/hooks/useAuth.ts | useGithubLogin()(复用 startGithubOAuth) |
front/src/hooks/useAccountBinding.ts | 绑定相关 hooks(useBindGithub 复用 popup 流程) |
front/src/constants/oauth.ts | OAuth 错误码 → 用户文案映射(page / popup 共用) |
front/public/oauth-popup.html | 暗色首帧静态回调页:processing 时完成 token 交换,随后通知主窗口并关闭 |
front/src/pages/AuthError.tsx | OAuth 错误落地页(page 模式兜底) |
front/src/components/auth/LoginForm.tsx | 「使用 GitHub 登录」按钮 |
front/src/components/setting/personal/AccountBinding.tsx | 账号绑定页 UI |
十五、总结
这是一个生产级的 BFF GitHub OAuth 集成:
Authlib+ PKCE S256 + HMAC state = 协议层安全users1:Nauth_methods+CheckConstraint= 数据层一致- login/bind 双流程 + 自动转 bind = 业务层防呆
- 错误码结构化 + 前端文案映射 = 用户体验层不泄露内部
- BFF 模式 + HttpOnly Cookie = 浏览器层零接触凭证
新增 provider 只需 3 处改动,扩展性已被现有代码结构验证。