跳到主要内容
ecdsa.com
jsonwebtoken (Node.js)JWT 库

错误信息

invalid signature

含义

令牌解析正常,结构也有效,但密码学检查失败了:用你提供的密钥无法验证针对 header.payload 的签名。要么这个密钥不是给令牌签名的那个,要么被签名的字节在签名之后发生了变化。

原因

修复方法

  1. 1.

    在两端计算密钥指纹

    对验证方实际加载的公钥计算哈希,并与颁发者的公钥对比。指纹不同就说明密钥已过时或用错了——这是最常见的原因,远多于其他——排查一步即可结束。

    js
    import { createHash, createPublicKey } from "node:crypto";
    
    // Run on the verifier, and on the issuer with its signing key: the outputs must match.
    const spki = createPublicKey(process.env.JWT_PUBLIC_KEY).export({ type: "spki", format: "der" });
    console.log(createHash("sha256").update(spki).digest("hex"));
  2. 2.

    让令牌的 kid 与验证密钥对应

    先不验证签名,只解码头部,把其中的 kid 与你手上的密钥对比。如果颁发者发布了 JWKS,就按 kid 查找密钥,而不是硬编码一个密钥。

    js
    const { header } = jwt.decode(token, { complete: true });
    console.log(header.kid, header.alg); // compare with your JWKS / configured key
  3. 3.

    让调试器指出哪里不匹配

    把令牌和公钥粘贴到 JWT 调试器中:它会在本地验证 ES256/ES384/ES512,并区分密钥错误、载荷被篡改和签名编码格式错误,而不只是给出一个简单的布尔值。

相关错误

浏览完整的签名错误库