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/

相关文章:

javascript - 降低 Node.js 套接字连接的超时时间

javascript - 如何修复 ' variable in loof with innerText'

javascript - 使用 Express 设置 React 应用程序

javascript - 使用 AngularJS $http.get 方法传递数据

node.js - 了解部署 Nodejs 应用程序时日志中的 Heroku bcrypt 错误

node.js - 使用 Sequelize

javascript - 如何在 Angular 5中使用ngoninit在前端设置日期值

node.js - 如何使用 super 测试、 Passport 和 JEST 在 cookie 中使用 jwt 测试身份验证

jwt - .net core web api jwtbearer 中间件如何使用身份验证提供程序验证 OpenID Connect token

javascript - 使用新的 accessToken 更新应用程序中的 accessToken 的最佳方法是什么?