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

查看:257
本文介绍了如何使用 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 时:

When I decode the JWT:

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

我得到了这个输出:

{ iat: 1561463667 }

但我排除了这个输出:

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

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

How do I get the user id from the token?

推荐答案

当整个输出为 { iat: 1561463667 } 时,这意味着当令牌被签.jsonwebtoken 包 通常会添加 iat(issuedAt,令牌的发行时间)作为默认声明.

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 或类似的,或者 subclaim,这是一个注册声明名称,用于识别主体:

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:

子"(subject) claim 标识作为主体的主体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天全站免登陆