OAuth2流程参考

授权码流程(含 PKCE)

1
生成 code_verifier(43-128 位随机字符串)并计算 code_challenge = BASE64URL(SHA256(code_verifier))
2
将用户重定向到授权端点,携带 response_type=codecode_challengecode_challenge_method=S256
3
用户认证并授权后,服务器携带 code 参数重定向回来
4
在令牌端点用 code 换取 token,同时发送 code_verifier
5
在 API 调用中使用 access_token;使用 refresh_token 续期

授权请求示例

GET https://auth.example.com/authorize? response_type=code &client_id=YOUR_CLIENT_ID &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback &scope=openid%20profile%20email &state=xyzABC123 &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM &code_challenge_method=S256

令牌交换请求

POST https://auth.example.com/token Content-Type: application/x-www-form-urlencoded grant_type=authorization_code &code=AUTHORIZATION_CODE &redirect_uri=https://app.example.com/callback &client_id=YOUR_CLIENT_ID &code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk # 响应 { "access_token": "eyJhbGci...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA", "id_token": "eyJhbGci..." }

授权类型对比

授权类型适用场景PKCE推荐
Authorization Code + PKCESPA、移动端、公共客户端必须
Authorization Code服务端 Web 应用可选是(建议加 PKCE)
Client Credentials机器对机器不适用
Device Code智能电视、CLI 工具不适用
Implicit旧版 SPA不适用否(已废弃)
Password旧版直接登录不适用否(已废弃)

令牌刷新

POST https://auth.example.com/token Content-Type: application/x-www-form-urlencoded grant_type=refresh_token &refresh_token=tGzv3JOkF0XG5Qx2TlKWIA &client_id=YOUR_CLIENT_ID

安全检查清单

检查项要求
state 参数使用随机不可猜测的值防止 CSRF
PKCE公共客户端必须使用(S256 方法)
redirect_uri注册并验证精确 URI,不允许通配符
Token 存储不要存入 localStorage;优先使用 httpOnly Cookie
Token 有效期access_token 短期(1h);刷新令牌轮换使用
Scope仅请求必要的最小权限范围