概述授权码+PKCE在OAuth 2.1中作为默认安全基线,结合刷新令牌轮换与复用检测,可显著降低令牌窃取与重放风险。通过S256挑战、一次性刷新令牌、缩短访问令牌有效期并启用密钥管理与审计,可在多端应用场景下获得更强的安全性与可观测性。关键实践与参数授权模式: `authorization_code` 配合 `code_verifier`挑战算法: `code_challenge_method=S256`刷新令牌策略: 轮换启用, 单次使用, 复用检测与吊销令牌寿命: `access_token` 5–15 分钟, `refresh_token` 7–30 天声明与头: `iss` `aud` `iat` `exp` `nbf` `jti` `kid`客户端认证: `private_key_jwt` 或 `mtls`范围与权限: 精准最小化 `scope`, 使用细粒度资源授权审计与速率限制: 登录与令牌事件审计, 刷新端点限速示例/配置/实现{ "issuer": "https://auth.example.com", "token_endpoint": "https://auth.example.com/oauth/token", "authorization_endpoint": "https://auth.example.com/oauth/authorize", "jwks_uri": "https://auth.example.com/.well-known/jwks.json", "rotation": { "refresh_token": { "enabled": true, "reuse_detection": true } }, "access_token_ttl": 900, "refresh_token_ttl": 2592000, "code_challenge_methods_supported": ["S256"], "token_endpoint_auth_methods_supported": ["private_key_jwt", "tls_client_auth"] } function base64UrlEncode(v) { return btoa(String.fromCharCode.apply(null, new Uint8Array(v))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") } async function createPkce() { const r = new Uint8Array(32) crypto.getRandomValues(r) const verifier = base64UrlEncode(r) const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)) const challenge = base64UrlEncode(digest) return { verifier, challenge } } curl -s -X POST https://auth.example.com/oauth/token \ -d grant_type=authorization_code \ -d code=CODE \ -d code_verifier=VERIFIER \ -d client_id=CLIENT_ID curl -s -X POST https://auth.example.com/oauth/token \ -d grant_type=refresh_token \ -d refresh_token=RT1 \ -d client_id=CLIENT_ID 验证令牌轮换: 使用首次刷新令牌获取新令牌后, 再次复用旧刷新令牌应返回错误并吊销新旧令牌生命周期: 校验 `exp` 与实际过期时间, 访问令牌在TTL后失效, 刷新令牌在TTL或复用后失效声明校验: 验证 `iss` `aud` `kid` 与JWKS匹配, `jti` 唯一速率限制: 刷新端点在高并发下按配额与漏桶策略限制审计事件: 登录、令牌签发、刷新、吊销事件完整记录并可查询注意事项停用隐式模式与资源所有者密码模式启用密钥轮换与失效列表, 定期审计密钥与令牌客户端安全存储刷新令牌, 移动端使用安全存储与设备绑定减少范围并按资源隔离, 结合后端细粒度授权

发表评论 取消回复