如何为移动端 PKCE 流程暴露 /authorize 代理端点?
解读
面试官真正想考察的是:
- 你是否理解 OAuth2.1 PKCE 在移动端“无后端密钥”场景下的安全诉求;
- 能否用 FastAPI 快速搭一个“无状态、无 Cookie、无会话”的纯代理端点,把移动端收到的 code_challenge、code_challenge_method 等参数原封不动转发给真正的授权服务器,并把授权服务器的 302 跳转再原样还给移动端;
- 是否知道国内常见合规要求,例如“个人信息不出境”“日志最小化”“HTTPS 强制双向校验”;
- 能否在 5 分钟内给出可运行、可单测、可灰度、可观测的代码骨架。
一句话:让移动端像调用本地服务一样完成 /authorize,却又不把 client_secret 落到客户端,同时满足国内安全审计与性能要求。
知识点
- PKCE 参数:code_challenge、code_challenge_method(S256/plain)、state、redirect_uri、client_id、scope、response_type=code。
- FastAPI 原生依赖注入与 BackgroundTasks,实现“请求级日志脱敏 + 异步上报”。
- Starlette 的 Request/Response 对象可直接流式读取 query 与 header,避免 Pydantic 模型校验带来的性能损耗。
- httpx.AsyncClient 连接池保持长连接,QPS 比 requests 高一个量级,适合代理场景。
- 国内合规三板斧:HTTPS 强制 TLS1.3 + 双向证书校验、敏感字段(手机号、IP)脱敏后落日志、返回头显式声明 x-content-type-options: nosniff。
- 灰度与可观测:通过 OpenTelemetry 的 FastAPI instrumentation 自动埋点,Prometheus 暴露 /metrics,配合 Nginx 网关做 1% 灰度。
- 异常处理:授权服务器 4xx/5xx 直接透传,但需把响应体中的 error_description 做正则脱敏,防止泄露内部地址。
- 压测指标:p99 延迟 < 30 ms(内网),内存占用 < 50 MB(1000 并发),CPU 占用 < 20%(4C8G 容器)。
答案
# main.py
import os
import re
import time
from typing import Dict, Any
import httpx
from fastapi import FastAPI, Request, Response, Query, HTTPException, BackgroundTasks
from fastapi.responses import RedirectResponse
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from prometheus_client import Counter, Histogram, generate_latest
import logging
# 合规:关闭 uvicorn 访问日志,避免敏感字段落地
logging.getLogger("uvicorn.access").disabled = True
logger = logging.getLogger("authorize_proxy")
# 指标
authorize_total = Counter("authorize_proxy_total", "Total authorize requests")
authorize_duration = Histogram("authorize_proxy_duration_seconds", "Duration of authorize proxy")
app = FastAPI(title="PKCE Authorize Proxy", version="1.0.0")
# 真正的授权服务器地址,通过环境变量注入,方便灰度切换
UPSTREAM_AUTHORIZE_URL = os.getenv("UPSTREAM_AUTHORIZE_URL", "https://auth.example.com/oauth/authorize")
# 创建全局异步连接池,keepalive_timeout 30s,limits 同并发数
httpx_client = httpx.AsyncClient(
timeout=httpx.Timeout(5.0, connect=2.0),
limits=httpx.Limits(max_keepalive_connections=100, max_connections=200),
)
# OpenTelemetry 自动埋点
FastAPIInstrumentor.instrument_app(app)
# 脱敏工具
SENSITIVE_KEYS = {"phone", "email", "id_card", "ip"}
def desensitize(query: Dict[str, Any]) -> Dict[str, Any]:
def _mask(v: str) -> str:
if len(v) <= 6:
return "*" * len(v)
return v[:2] + "*" * (len(v) - 4) + v[-2:]
return {k: _mask(v) if k in SENSITIVE_KEYS else v for k, v in query.items()}
# 代理端点
@app.get("/authorize")
async def authorize_proxy(
request: Request,
background: BackgroundTasks,
response_type: str = Query(..., regex="^code$"),
client_id: str = Query(..., min_length=1),
redirect_uri: str = Query(...),
scope: str = Query(None),
state: str = Query(None),
code_challenge: str = Query(..., min_length=43, max_length=128),
code_challenge_method: str = Query("S256", regex="^(S256|plain)$"),
):
start = time.time()
authorize_total.inc()
# 1. 构造上游请求参数,完全透传
params = {
"response_type": response_type,
"client_id": client_id,
"redirect_uri": redirect_uri,
"scope": scope,
"state": state,
"code_challenge": code_challenge,
"code_challenge_method": code_challenge_method,
}
# 2. 异步脱敏日志
background.add_task(
logger.info,
"authorize_proxy request: %s",
desensitize(params),
)
# 3. 转发
try:
upstream_resp = await httpx_client.get(
UPSTREAM_AUTHORIZE_URL,
params=params,
headers={"user-agent": request.headers.get("user-agent", "")},
follow_redirects=False, # 关键:不自动跟随 302,让移动端自己处理
)
except httpx.ReadTimeout:
raise HTTPException(status_code=504, detail="authorize timeout")
# 4. 透传状态码、header、body
headers = {
k: v
for k, v in upstream_resp.headers.items()
if k.lower() not in {"content-encoding", "content-length", "transfer-encoding"}
}
# 5. 如果上游返回 302,把 location 原样返回
if upstream_resp.status_code == 302:
location = upstream_resp.headers.get("location")
authorize_duration.observe(time.time() - start)
return RedirectResponse(url=location, status_code=302, headers=headers)
# 6. 其他状态码直接透传
authorize_duration.observe(time.time() - start)
return Response(
content=upstream_resp.content,
status_code=upstream_resp.status_code,
headers=headers,
)
# 健康检查
@app.get("/healthz")
async def healthz():
return {"status": "ok"}
# Prometheus 指标
@app.get("/metrics")
async def metrics():
return Response(content=generate_latest(), media_type="text/plain")
# 优雅关闭连接池
@app.on_event("shutdown")
async def shutdown():
await httpx_client.aclose()
运行方式(生产用 gunicorn + uvicorn.workers.UvicornWorker):
UPSTREAM_AUTHORIZE_URL=https://auth.company.cn/oauth/authorize \
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000
压测验证:
wrk -t4 -c100 -d30s "http://localhost:8000/authorize?response_type=code&client_id=demo&redirect_uri=http%3A//mobile&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256"
预期 p99 < 30 ms,内存稳定。
拓展思考
- 灰度策略:在 Nginx 层按 HTTP Header x-gray=1 路由到新版代理容器,FastAPI 本身无状态,灰度回滚零成本。
- 缓存优化:授权服务器返回的 302 location 里通常带一次性 code,天然不可缓存;但 client_id 白名单可缓存到 Redis,减少一次配置中心查询。
- 防重放:在代理层增加一次性 JWT(JTI + exp=10s)校验,移动端先调 /nonce 拿 JWT,再带 JWT 访问 /authorize,可抵御短窗口重放,且对 PKCE 无侵入。
- 多租户:通过子域或 Path 参数区分租户,FastAPI 的 APIRouter 可按租户动态挂载不同 upstream,实现“一套代码,多授权源”。
- 国内合规进阶:若授权服务器在境外,需在代理层做“数据出境安全评估”备案,日志不落盘,直接走 Kafka 到境内合规日志平台,且对个人敏感字段做 SM4 加密。