如何解决RS256算法下的JsonWebTokenError: invalid signature问题?
验证JWT时持续出现
JsonWebTokenError: invalid signature错误排查 我在验证JWT时一直遇到JsonWebTokenError: invalid signature错误。登录/注册生成的token在在线工具上搭配对应公私钥和RS256算法能正常验证签名,但自己的认证中间件始终报错。
认证中间件代码
module.exports.authMiddleware = (req, res, next) => { const tokenParts = req.headers.authorization.split(" "); console.log(tokenParts) // verifying that the token from authorization header is in correct format if(tokenParts[0] === "Bearer" && tokenParts[1].match(/\S+\.\S+\.\S+/) !== null){ try { const verification = jsonwebtoken.verify( tokenParts[1], PUBLIC_KEY, {algorithms: ["RS256"]} ) req.jwt = verification next() } catch (error) { console.log(error) res.status(401).json({ success: false, message: "You are not authorized auth" }) } } else { res.status(401).json({ success: false, message: "You are not authorized", }) } }
公私钥生成函数
const genKeyPair = () => { const keyPair = crypto.generateKeyPairSync('rsa', { modulusLength: 4096, // bits - standard for RSA keys publicKeyEncoding: { type: 'pkcs1', // "Public Key Cryptography Standards 1" format: 'pem' // Most common formatting choice }, privateKeyEncoding: { type: 'pkcs1', // "Public Key Cryptography Standards 1" format: 'pem' // Most common formatting choice } }); // Create the public key file fs.writeFileSync("keys/id_rsa_pub.pem", keyPair.publicKey); // Create the private key file fs.writeFileSync("keys/id_rsa_priv.pem", keyPair.privateKey); } genKeyPair()
可能的排查方向
- 公钥加载完整性:检查
PUBLIC_KEY的加载逻辑,确保完整读取PEM文件内容。比如使用fs.readFileSync("keys/id_rsa_pub.pem", "utf8"),避免直接读取Buffer未转换为字符串,导致密钥格式错误。 - token一致性校验:在中间件中打印
tokenParts[1],和生成的原始token逐字符对比,确认传输过程中没有被截断、编码或混入额外字符。 - 生成与验证的算法一致性:确认生成token时使用的是RS256算法,和验证时指定的
{algorithms: ["RS256"]}完全匹配,若生成时用了其他算法(如HS256)会直接导致签名验证失败。 - 密钥路径与权限:检查公钥文件的路径是否正确,程序是否有读取该文件的权限,避免读取到空内容或错误的文件。
- 公钥格式兼容性:虽然在线工具支持PKCS1格式,但可以尝试将公钥转换为PKCS8格式测试,转换命令示例:
openssl rsa -in id_rsa_pub.pem -pubin -outform PEM -out id_rsa_pub_pkcs8.pem。
内容的提问来源于stack exchange,提问作者Fun Strike
相关产品推荐
相关产品推荐

