How to get user id using jwt token

hari prasanth picture hari prasanth · Jun 25, 2019 · Viewed 10.3k times · Source

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?

Answer

jps picture jps · Jun 25, 2019

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)