9

I tried to get user id from a JWT token. I got a JWT token and sucessfully verified it, but it doesn't return an id.

When I decode the JWT:

const decoded = jwt.verify(token, config.get('jwtPrivateKey'));  
var userId = decoded.id  
console.log(decoded)  

I got this output:

{ iat: 1561463667 }

But I excepted this output:

id :"*****************"

How do I get the user id from the token?

jps
  • 20,041
  • 15
  • 75
  • 79
hari prasanth
  • 716
  • 1
  • 15
  • 35

1 Answers1

11

When the whole output is { iat: 1561463667 }, it means, that no extra payload/claims were added when the token was signed. The jsonwebtoken package usually adds iat (issuedAt, the time when the token was issued) as a default claim.

In simple words: you can only decode claims, that were added before.

To add more claims, try this code (when you're in control of the code which issues the token):

let payload = { "id" : "1"};
let token = jwt.sign( payload,'secret',  { noTimestamp:true, expiresIn: '1h' });

Here I added an expiry time (exp), and set the option noTimestamp to suppress the automatically added iat claim.

The result looks like this:

{
 "id": "1",
 "exp": 1561471747
}

and the token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJleHAiOjE1NjE0NzI0MzV9.jmKyITRoxLl0fy0-rrwgPOA_iRgGQu8W4Cc6dPupOMA

Then you can get the id as you have already shown in your question:

const decoded = jwt.verify(token, "your secret or key");  
var userId = decoded.id  
console.log(userId)  

You can also paste the above shown JWT or your token into the https://jwt.io debugger, to inspect the token and see the structure and the actual claim names. Maybe there's no id, but a userId or similar, or a subclaim, which is a registerd claim name to be used to identify the principal:

The "sub" (subject) claim identifies the principal that is the subject of the JWT.

It might also happen, that the token contains nested objects, e.g.:

{
  "user_data": 
    {
      "user_id": "1",
      "user_name: "superuser"
    },
 "exp": 1561471747
}

then you get the user_id this way:

const decoded = jwt.verify(token, "your secret or key");  
var userId = decoded.user_data.user_id  
console.log(userId)  
Community
  • 1
  • 1
jps
  • 20,041
  • 15
  • 75
  • 79
  • In this, you have skip token expiry time. – Sachin Shah Jun 25 '19 at 12:32
  • of course `exp`should be added, but that's not the point of the question here. – jps Jun 25 '19 at 12:33
  • I think that is the point of the question, Hear he got expiry time when he used `decode.id`. He got expiry time value when expected output is user's id. – Sachin Shah Jun 25 '19 at 12:36
  • no, he didn't get expiry time, he got, as I explained, the iat (issued at) time. That's when the token was signed. And, as I said, the framework adds this automatically. I added the code for expiryTime in my answer. – jps Jun 25 '19 at 12:38