--- title: OAuth Token Exchange与Audience映射(RFC8693)最佳实践 keywords: - Token Exchange - RFC8693 - audience - subject_token - actor_token description: 通过RFC8693的令牌交换实现audience映射与最小权限,规范跨服务调用的令牌转换与范围控制。 categories: - 文章资讯 - 技术教程 --- 背景与价值 跨服务调用需要合适的audience与范围。令牌交换可安全地转换令牌并限制权限。 统一规范 - 必填字段:`subject_token`、`subject_token_type`、`requested_token_type`。 - Audience映射:明确目标 `audience` 与缩小 `scope`。 - 响应校验:验证返回令牌的 `aud`、`exp` 与类型。 核心实现 令牌交换请求与校验 ```ts type ExchangeReq = { endpoint: string; auth: string; subject_token: string; subject_token_type: string; requested_token_type: string; audience?: string; scope?: string } type ExchangeRes = { access_token: string; issued_token_type: string; token_type: string; expires_in: number } async function exchangeToken(req: ExchangeReq): Promise { const body = new URLSearchParams() body.set('subject_token', req.subject_token) body.set('subject_token_type', req.subject_token_type) body.set('requested_token_type', req.requested_token_type) if (req.audience) body.set('audience', req.audience) if (req.scope) body.set('scope', req.scope) const r = await fetch(req.endpoint, { method: 'POST', headers: { 'Authorization': req.auth, 'Content-Type': 'application/x-www-form-urlencoded' }, body }) if (!r.ok) return null const j = await r.json() if (typeof j.access_token !== 'string' || typeof j.issued_token_type !== 'string' || typeof j.token_type !== 'string' || typeof j.expires_in !== 'number') return null return j as ExchangeRes } ``` 落地建议 - 令牌交换时明确目标audience并缩小scope,确保最小权限原则。 - 对返回令牌类型与有效期进行校验,并配合网关门禁使用。 验证清单 - 请求是否包含必要字段;返回令牌类型与 `expires_in` 是否合理。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部