核心价值在 Edge 环境通过 `crypto.subtle` 验证 RS256 签名,避免引入重型依赖。对 `exp/aud/iss` 进行严格校验并与 Cookie 会话结合,提升安全性与一致性。验证实现export const runtime = 'edge'
const JWK: JsonWebKey = { kty: 'RSA', n: 'BASE64URL_N', e: 'AQAB' }
const AUD = 'web'
const ISS = 'https://auth.example.com'
function b64urlToBytes(s: string) {
s = s.replace(/-/g, '+').replace(/_/g, '/')
const pad = s.length % 4 === 0 ? '' : '='.repeat(4 - (s.length % 4))
const raw = atob(s + pad)
const buf = new Uint8Array(raw.length)
for (let i = 0; i < raw.length; i++) buf[i] = raw.charCodeAt(i)
return buf
}
async function verifyRS256(jwt: string) {
const [h, p, s] = jwt.split('.')
if (!h || !p || !s) return null
const data = new TextEncoder().encode(`${h}.${p}`)
const sig = b64urlToBytes(s)
const key = await crypto.subtle.importKey('jwk', JWK, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify'])
const ok = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, sig, data)
if (!ok) return null
const payload = JSON.parse(new TextDecoder().decode(b64urlToBytes(p)))
return payload
}
export async function GET(req: Request) {
const auth = req.headers.get('authorization') || ''
const token = auth.startsWith('Bearer ') ? auth.slice(7) : ''
const payload = token ? await verifyRS256(token) : null
if (!payload) return new Response('Unauthorized', { status: 401 })
const now = Math.floor(Date.now() / 1000)
if (payload.exp && now >= payload.exp) return new Response('Expired', { status: 401 })
if (payload.aud !== AUD || payload.iss !== ISS) return new Response('Unauthorized', { status: 401 })
const sid = crypto.randomUUID()
return Response.json({ ok: true, sub: payload.sub }, {
headers: {
'Set-Cookie': `sid=${sid}; Path=/; HttpOnly; SameSite=Lax`,
'Cache-Control': 'no-store',
},
})
}
治理建议使用 JWK 公钥验证 RS256,私钥只在身份提供方;对 `kid` 做密钥轮换管理。会话 Cookie 设置 `HttpOnly/SameSite`,必要时 `Secure`;与 CSRF 防护协同。结论在 Edge 路由中以原生 Web Crypto 验证 JWT 并结合 Cookie 会话治理,具备高性能与低依赖的优势,适合现代前端架构的安全入口。

发表评论 取消回复