背景与价值内省可验证令牌状态与声明。结合短TTL缓存与门禁策略,可在网关层提升性能并保持安全。统一规范必要字段:`active`、`exp`、`client_id` 必须存在且合法。TTL门禁:缓存TTL不超过剩余有效期且设短上限(如30秒)。失败阻断:内省失败或响应不合法时拒绝访问。核心实现内省请求与缓存type IntrospectionRes = { active: boolean; exp: number; client_id: string; scope?: string }

class Cache<T> { data = new Map<string, { v: T; until: number }>(); get(k: string): T | undefined { const e = this.data.get(k); if (!e) return; if (Date.now() > e.until) { this.data.delete(k); return } return e.v } set(k: string, v: T, ttlMs: number) { this.data.set(k, { v, until: Date.now() + ttlMs }) } }

async function introspect(token: string, endpoint: string, auth: string): Promise<IntrospectionRes | null> {

const r = await fetch(endpoint, { method: 'POST', headers: { 'Authorization': auth, 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'token=' + encodeURIComponent(token) })

if (!r.ok) return null

const j = await r.json()

if (typeof j.active !== 'boolean' || typeof j.exp !== 'number' || typeof j.client_id !== 'string') return null

return j as IntrospectionRes

}

function ttlFor(exp: number, maxMs = 30000): number { const remain = Math.max(0, exp * 1000 - Date.now()); return Math.min(remain, maxMs) }

async function gate(token: string, endpoint: string, auth: string, cache: Cache<IntrospectionRes>): Promise<boolean> {

const c = cache.get(token)

if (c) return c.active && c.exp * 1000 > Date.now()

const res = await introspect(token, endpoint, auth)

if (!res || !res.active) return false

cache.set(token, res, ttlFor(res.exp))

return true

}

落地建议在网关层执行令牌内省并短TTL缓存,保障性能与安全;失败立即阻断。TTL不超过令牌剩余有效期与固定上限,避免过期令牌被命中。验证清单内省响应是否包含 `active/exp/client_id` 且合法;TTL是否短且不超过剩余有效期。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部