Jsonwebtoken verify always return only {iat: xxx }
Asked Answered
G

3

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: [email protected],}

Is there something I am missing ?

Gladdie answered 9/8, 2016 at 7:0 Comment(0)
H
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 "[email protected]" then the output would be;

{ email: '[email protected]', 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.

Homologous answered 9/8, 2016 at 7:25 Comment(1)
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}` }.Naima
T
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":"[email protected]"}

Terrilyn answered 1/5, 2022 at 19:6 Comment(0)
V
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
}
Vicereine answered 9/8, 2016 at 7:18 Comment(3)
What OP got there is a valid example. If no callback function is specified then jwt.verify operates synchronously.Homologous
I see. Then, I do not see a problem with the initial code. He might aswell try this code and report if it solves the problem.Vicereine
Thanks @NikxDa, but nope :(Gladdie

© 2022 - 2024 — McMap. All rights reserved.