node.js - JWT 负载中应该包含多少信息?

标签 node.js mean-stack jwt

我正在使用 Mean 堆栈构建抽认卡应用程序并尝试模仿本教程中遵循的过程 https://thinkster.io/mean-stack-tutorial#wiring-everything-up .

当新用户注册时,我想在用户对象中返回该用户的信息:正在研究的当前和最近的卡片组、正在研究的当前和最近的卡片等。

我的问题是这些信息中有多少应该进入 JWT 负载?

在 thinkster.io 教程中,JWT 的负载仅包含用户 ID、用户名和到期日期。我担心额外的信息是否不应进入 JWT,因为这会使 JWT 太大。然后我是否只将 JWT 与用户对象一起发回,该用户对象是在使用 mongoose.save 方法保存用户后返回的?该策略听起来与以下引用相匹配:

https://auth0.com/blog/2014/01/27/ten-things-you-should-know-about-tokens-and-cookies/#token-size

Every time you make an API request you have to send the token in the Authorization header.

Depending on how much information you store in that token, it could get big. On the other hand, session cookies usually are just an identifier (connect.sid, PHPSESSID, etc.) and the rest of the content lives on the server (in memory if you just have one server or a database if you run on a server farm).

Now, nothing prevents you from implementing a similar mechanism with tokens. The token would have the basic information needed and on the server side you would enrich it with more data on every API call. This is exactly the same thing cookies will do, with the difference that you have the additional benefit that this is now a conscious decision, you have full control, and is part of your code.

我试图从 thinkster.io 模仿的/register 路由代码如下:

router.post('/register', function(req, res, next){
  if(!req.body.username || !req.body.password){
    return res.status(400).json({message: 'Please fill out all fields'});
  }

  var user = new User();

  user.username = req.body.username;

  user.setPassword(req.body.password)

  user.save(function (err){
    if(err){ return next(err); }

    return res.json({token: user.generateJWT()})
  });
});

我能不能把底部的保存方法部分编辑成这样:

user.save(function (err, user){
    if(err){ return next(err); }

    return res.json({token: user.generateJWT(), 
                     user: user})
  });

还是应该将所有额外的用户信息都放入 JWT 中,只传回 JWT?

最佳答案

您需要根据您的安全需求来使用。

例如,对于我的应用程序,我确实以您为榜样。 token 存储在客户端 cookie 中,在身份验证中,我做一件事:

  • 解码 JWT 并使用 _id 和另一个主键填充 request.user。
  • 发回 token 和用户信息。

可以在 API 调用中公开相同的用户信息。需要注意的一件重要事情是我的系统不需要总是更新和同步。因此,我的客户端用户只会在登录时和特定的 GET 请求时获取用户数据。

您不需要在 JWT 中混入大量垃圾。还需要解码。

关于node.js - JWT 负载中应该包含多少信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33420049/

相关文章:

node.js - ( Mongoose )如何从 session 中获取 user._id 以便发布包含此 user._id 的数据

java - 我可以在使用 Spring Security 进行身份验证时获取请求参数吗?

javascript - 无法抓取 ally.com

node.js - Node package.json 依赖

node.js - Windows 10 上的 node-sass 安装问题

node.js - 在每个请求中包含承载 token 并保持用户登录

c# - 将自定义验证添加到 ASP.NET Core 的 JWT token ?

javascript - 奇怪的错误: Cowardly refusing to pack object with circular reference

node.js - 应如何设置高需求应用程序的 node.js 堆栈?

node.js - 在客户端下载压缩文件夹在 Angular+Node 中不起作用(MEAN)