如何使用jwt令牌获取用户ID [英] How to get user id using jwt token

查看:1599
本文介绍了如何使用jwt令牌获取用户ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

当我解码JWT时:

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

我得到了这个输出:

{ iat: 1561463667 }

但是我排除了以下输出:

But I excepted this output:

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

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

How do I get the user id from the token?

推荐答案

当整个输出为{ iat: 1561463667 }时,表示在对令牌进行签名时未添加额外的有效负载/声明. jsonwebtoken软件包通常添加

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' });

在这里,我添加了到期时间(exp) ,并设置选项noTimestamp以禁止自动添加iat声明.

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

结果如下:

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

和令牌:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJleHAiOjE1NjE0NzI0MzV9.jmKyITRoxLl0fy0-rrwgPOA_iRgGQu8W4Cc6dPupOMA

然后,您可以获取问题中已经显示的ID:

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)  

您还可以将上面显示的JWT或令牌粘贴到 https://jwt.io 调试器中,检查令牌并查看结构和实际的索赔名称.也许没有id,但是没有userId或类似名称,或者是 sub claim ,它是用于标识主体的注册的索赔名称:

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:

"sub" (主旨)声明指出的主体是 JWT的主题.

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
}

然后您通过以下方式获取user_id:

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)  

这篇关于如何使用jwt令牌获取用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆