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路由代码如下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1router.post('/register', function(req, res, next){
2  if(!req.body.username || !req.body.password){
3    return res.status(400).json({message: 'Please fill out all fields'});
4  }
5
6  var user = new User();
7
8  user.username = req.body.username;
9
10  user.setPassword(req.body.password)
11
12  user.save(function (err){
13    if(err){ return next(err); }
14
15    return res.json({token: user.generateJWT()})
16  });
17});
18

我可以编辑底部的保存方法部分,看起来像这样:


1
2
3
4
5
6
7
1user.save(function (err, user){
2    if(err){ return next(err); }
3
4    return res.json({token: user.generateJWT(),
5                     user: user})
6  });
7

或者是否应将所有额外的用户信息放入JWT并且只传回JWT?

您需要根据您的安全需要使用.

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

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

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

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

给TA打赏
共{{data.count}}人
人已打赏
安全技术

使用工厂模式、策略模式实现BASE64,MD5,SHA,HMAC,DES各种加密算法

2021-8-18 16:36:11

安全技术

C++ 高性能服务器网络框架设计细节

2022-1-11 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索