How to get user id using jwt token

后端 未结 1 1534
抹茶落季
抹茶落季 2020-12-04 00:47

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:



        
相关标签:
1条回答
  • 2020-12-04 01:23

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

    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)  
    
    0 讨论(0)
提交回复
热议问题