8

According to documentation, https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback, jwt.verify will returns decode payload, I run the simple script:

var token = jwt.sign({email: req.body.email,}, 's3cr3t');
var decoded = jwt.verify(token, 's3cr3t');
console.log(decoded)

but it only output like: { iat: 1470725598 }

I expect the output should be like {email: myemail@domain.com,}

Is there something I am missing ?

egig
  • 4,370
  • 5
  • 29
  • 50

3 Answers3

19

I was not able to mimic your problem until I set the property req.body.email to undefined.

Example:

var jwt = require('jsonwebtoken');
var token = jwt.sign({email: undefined}, 's3cr3t');
var decoded = jwt.verify(token, 's3cr3t'); 

With it been undefined, the output would look like this;

{ iat: 1470727340 }

and this matches exactly what you were having which cause me to suspect your main issue was just with the property req.body.email been undefined.

Assuming req.body.email is correctly set to "myemail@domain.com" then the output would be;

{ email: 'myemail@domain.com', iat: 1470727500 }

Just a side note here. You might want to consider wrapping the .verify method inside a try-catch clause, as shown in the documentation. This is useful for verifying and throwing error when a token is invalid.

Samuel Toh
  • 18,006
  • 3
  • 24
  • 39
  • Remind that `email` MUST be a String, I've got the same issue because my key's value was an int and not a string (I just replaced `{ key: value }` by `{ key: \`${value}\` }`. – Paul-Marie May 08 '20 at 00:35
1

I Know this is an old question but there's no clear solution that shows how to reproduce the problem. I also recently encountered the same problem: Decoded values where like {iat:xxxz}

This is why:

Sending a post request without the "Content-type: application/json" will result in req.body.email be undefined. That's not the value your trying to jwt.verify so the unexpected behavior.

Solved adding the "Content-type application/json" on the headers of the post request. And make sure you send de object in valid json format, properties must be like:

{"email":"mi@email.com"}

cigien
  • 57,834
  • 11
  • 73
  • 112
0

The verify-function takes a third parameter, function (err, decoded). Your code should look like this:

jwt.verify (token, "s3cr3t", function (err, decoded) {
    if (err) throw err;

    // decoded object with your data
}
NikxDa
  • 4,137
  • 1
  • 26
  • 48