← 中文资源

简体中文版本

Web 应用 JWT 认证完整指南

令牌结构、签名算法、刷新令牌、轮换和吊销策略,帮助在生产 Web 应用中安全使用 JWT。

阅读英文原文

引言

JWT 是一种签名令牌格式,不是完整的认证方案。安全性取决于算法选择、令牌生命周期、存储位置、刷新与吊销设计,以及服务端是否真正校验声明。

结构与算法

JWT 由 header、payload 和 signature 组成,payload 只是 Base64URL 编码,任何人都能读取。优先使用非对称算法(RS256、EdDSA)以便验证方只持有公钥;使用 HMAC 时密钥绝不能进入客户端。验证时固定算法,防止算法混淆。

访问与刷新令牌

访问令牌短命(数分钟到十几分钟),用于调用 API;刷新令牌长命但只发给认证端点。刷新令牌应轮换,并检测重复使用:旧令牌再次出现可能意味着泄露,应吊销整个令牌族。

存储与 XSS

localStorage 易受 XSS 读取;HttpOnly、Secure、SameSite cookie 能降低风险,但需要 CSRF 防护。无论哪种方式,XSS 都能代表用户发起请求,因此输出编码和 CSP 仍是基础。

吊销与密钥轮换

无状态 JWT 难以即时吊销。使用短生命周期、令牌版本或拒绝列表,并让高风险操作重新认证。通过 JWKS 发布公钥并支持 kid 轮换,保留旧公钥直到所有旧令牌过期。

结论

JWT 适合无状态服务间认证和短期访问令牌。把刷新、吊销、存储和密钥轮换作为一个整体设计,而不是只关注签名本身。

代码示例

// Header
{ "alg": "HS256", "typ": "JWT" }
// Payload (claims)
{
  "sub": "user-42",
  "iss": "https://auth.example.com",
  "aud": "https://api.example.com",
  "role": "admin",
  "iat": 1736832000,
  "exp": 1736835600,
  "jti": "f1c2d3e4-..."
}
import jwt from "jsonwebtoken";

// Signing (auth service holds the private key)
const token = jwt.sign(
  { sub: userId, role: "user" },
  process.env.JWT_PRIVATE_KEY!, // PEM-encoded RSA private key
  { algorithm: "RS256", expiresIn: "15m", issuer: "auth.example.com", audience: "api.example.com", jwtid: crypto.randomUUID() },
);

// Verifying (API service holds only the public key)
const claims = jwt.verify(token, process.env.JWT_PUBLIC_KEY!, {
  algorithms: ["RS256"], // pin the algorithm — never omit this
  issuer: "auth.example.com",
  audience: "api.example.com",
});
async function login(userId: string, res: Response) {
  const accessToken = signAccessToken(userId);
  const refreshToken = await issueRefreshToken(userId); // store hash in DB
  res.cookie("access_token", accessToken, {
    httpOnly: true, secure: true, sameSite: "strict", maxAge: 15 * 60 * 1000,
  });
  res.cookie("refresh_token", refreshToken, {
    httpOnly: true, secure: true, sameSite: "strict", path: "/auth/refresh", maxAge: 7 * 24 * 60 * 60 * 1000,
  });
}
async function refresh(oldRefreshToken: string) {
  const hash = sha256(oldRefreshToken);
  const record = await db.refreshToken.findUnique({ where: { hash } });
  if (!record) throw new AuthError("invalid token");
  if (record.revoked) {
    // Reuse detected — revoke the whole family.
    await db.refreshToken.updateMany({ where: { userId: record.userId }, data: { revoked: true } });
    throw new AuthError("reuse detected; all sessions revoked");
  }
  if (record.expiresAt < new Date()) throw new AuthError("expired");
  // Rotate: consume old, issue new.
  await db.refreshToken.update({ where: { id: record.id }, data: { revoked: true } });
  const newRefresh = crypto.randomBytes(32).toString("base64url");
  await db.refreshToken.create({ data: { userId: record.userId, hash: sha256(newRefresh), expiresAt: addDays(new Date(), 7) } });
  return { accessToken: signAccessToken(record.userId), refreshToken: newRefresh };
}
async function verifyWithRevocation(token: string) {
  const claims = jwt.verify(token, publicKey, { algorithms: ["RS256"], audience: "api.example.com" }) as Claims;
  const user = await db.user.findUnique({ where: { id: claims.sub }, select: { tokenVersion: true } });
  if (claims.v !== user.tokenVersion) throw new AuthError("token superseded");
  return claims;
}
import { createRemoteJWKSet } from "jose";

// A verifier that fetches and caches the JWKS, selecting the key by kid.
const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));

async function verify(token: string) {
  const { payload, protectedHeader } = await jwtVerify(token, JWKS, {
    algorithms: ["RS256"],
    issuer: "auth.example.com",
    audience: "api.example.com",
  });
  return payload; // the key was selected by protectedHeader.kid automatically
}