4
votes

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.

2
well, you're adding your whole user record to the token (bad enough), and that record even contains a token that you stored into your db before (even worse). I suggest to add only a few necessary claims, e.g. the user id and an expiration time to the token. You can insprect your token at jwt.io - jps
Okay, I'll check out jwt.io. I forgot to add that jwt.decode() works just fine, but jwt.verify() does not, which seems strange to me. - Brian
I just used jwt.io and it verified the signature. I've also changed the token above to remove the user info. - Brian
Yes, you are correct; I was mistaken about it being verified. I will post the new code and token in a bit. I'm having trouble removing all of the user information, which I would rather not have available on SO. Thanks for the help, by the way. - Brian
you're welcome. Pls. never post real data, only test data here. You can flag your post "in need of moderator intervention" and explain the problem. I think they can help. - jps

2 Answers

0
votes

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

-3
votes

I also had the same problem ,I solved it by converting token using toString method.

await jwt.verify(token.split(" ")[1].toString(),'secret');