Why is jsonwebtoken throwing an "invalid signature" error?

Brian picture Brian · Jul 29, 2019 · Viewed 9.9k times · Source

I am using the jsonwebtoken package (https://github.com/auth0/node-jsonwebtoken) to handle JWTs in my project. No matter what I try, it gives me this error: name: 'JsonWebTokenError', message: 'invalid signature'

Here is where I sign the 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)
      }
    })
  })
}

And here is where I try to verify it:

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 {
    ...
    }
  })
}

I'm using 'helloworld' as a stand in for my secret key. I suspect the problem is with the secret key but like i said, I'm not sure what is going on behind the scenes that is causing this error.

If I use jwt.decode(token, 'helloworld') I get all the right information back. But I get the error when i use jwt.verify().

Any help is much appreciated. Let me know if you need any more information from my code.

Answer

Devendra Pratap Singh picture Devendra Pratap Singh · Apr 28, 2021

Try using a base64 text as a key. I was also facing this very problem but using base64 key solved my problem.