背景与价值跨服务调用需要合适的audience与范围。令牌交换可安全地转换令牌并限制权限。统一规范必填字段:`subject_token`、`subject_token_type`、`requested_token_type`。Audience映射:明确目标 `audience` 与缩小 `scope`。响应校验:验证返回令牌的 `aud`、`exp` 与类型。核心实现令牌交换请求与校验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<ExchangeRes | null> { 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` 是否合理。

发表评论 取消回复