为什么 jsonwebtoken 抛出“无效签名”错误?

Bri*_*ian 5 node.js jwt express-jwt

我正在使用 jsonwebtoken 包(https://github.com/auth0/node-jsonwebtoken)来处理项目中的 JWT。无论我尝试什么,它都会给我这个错误:name: 'JsonWebTokenError', message: 'invalid signature'

这是我签署 JWT 的地方:

const addBearerToken = (myUser, cb) => {
  jwt.sign({user: myUser, userId: myUser.id}, 'helloworld', (err, token) => {
    if (err) return (err, null)
    userRepo.update(myUser._id, {authToken: token}, (err, myUser) => {
      if (err) {
        return cb(err, null)
      } else {
        return cb(null, token)
      }
    })
  })
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试验证的地方:

const checkForJWT = (req, res, next) => {
  let bearerHeader = req.header('Authorization').split(' ')
  let token = bearerHeader[1]
  console.log(token + '  ||  token')
  jwt.verify(token, 'helloworld', (err, decoded) => {
    if (err) {
      console.log(err)
      return (err, null) // this is where the error is thrown
    } else {
    ...
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

我使用“helloworld”作为我的密钥的替代。我怀疑问题出在密钥上,但正如我所说,我不确定幕后发生了什么导致此错误。

如果我使用 jwt.decode(token, 'helloworld') 我会得到所有正确的信息。但是当我使用 jwt.verify() 时出现错误。

任何帮助深表感谢。如果您需要我的代码中的更多信息,请告诉我。

小智 0

尝试使用 Base64 文本作为密钥。我也面临这个问题,但使用 base64 密钥解决了我的问题。

  • a)既不清楚你真正遇到了什么问题,也不清楚base64编码如何解决它,我怀疑它会对OP有帮助。b) Base64 编码的字符串可以有 0、1 或 2 个填充字符 (=)。Base64 字符串总是以 == 结尾,这是一个常见的误解 (2认同)