OAuth2流程参考
授权码流程(含 PKCE)
1
生成
code_verifier(43-128 位随机字符串)并计算 code_challenge = BASE64URL(SHA256(code_verifier))2
将用户重定向到授权端点,携带
response_type=code、code_challenge、code_challenge_method=S2563
用户认证并授权后,服务器携带
code 参数重定向回来4
在令牌端点用 code 换取 token,同时发送
code_verifier5
在 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 + PKCE | SPA、移动端、公共客户端 | 必须 | 是 |
| 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 | 仅请求必要的最小权限范围 |