如何使用 jwt 令牌获取用户 ID

How to get user id using jwt token

我试图从 JWT 令牌中获取用户 ID。我得到了一个 JWT 令牌并成功验证了它,但它没有 return id。

当我解码 JWT 时:

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

我得到了这个输出:

{ iat: 1561463667 }

但我排除了这个输出:

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

如何从令牌中获取用户 ID?

当整个输出为 { iat: 1561463667 } 时,这意味着在签署令牌时没有添加额外的 payload/claims。 jsonwebtoken package usually adds iat (issuedAt,令牌发布的时间)作为默认声明。

简而言之:您只能解码之前添加的声明。

要添加更多声明,请尝试此代码(当您控制发布令牌的代码时):

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

这里我添加了一个expiry time (exp),并设置选项noTimestamp来抑制自动添加的iat声明。

结果如下所示:

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

和令牌:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJleHAiOjE1NjE0NzI0MzV9.jmKyITRoxLl0fy0-rrwgPOA_iRgGQu8W4Cc6dPupOMA

然后你可以得到你已经在你的问题中显示的id:

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

您也可以将上面显示的 JWT 或您的令牌粘贴到 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,这是一个注册的声明名称,用于识别委托人:

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

也可能发生,令牌包含嵌套对象,例如:

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

然后你得到 user_id 这样:

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