node.js – JWT有效负载应该有多少信息?

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

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

我的问题是这些信息中有多少应该用于JWT有效载荷?

在thinkster.io教程中,JWT的有效负载仅包含user_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?

最佳答案 您需要根据您的安全需要使用.

例如,对于我的应用程序,我会按照您的示例进行操作.令牌存储在客户端cookie中,在身份验证中,我做了一件事:

>解码JWT并使用_id和另一个主键填充request.user.
>发回令牌和用户信息.

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

您不需要在JWT中混合大量垃圾.它需要解码.

点赞