只使用JWT将会话数据保留在后端

我在我的应用程序上使用智威汤逊,我定义我的说法是这样的:

const claims = { iss: process.env.DOMAIN, scope: "game", email: user.get("email") }; 

我validation这样的令牌:

 nJwt.verify(socket.handshake.query.token, app.get("jwt.secret"), (err, decoded) => { if (err) return; console.log(decoded.body.email); // doge@doge.com }); 

但是,这迫使我将会话数据添加到claims对象中。 相反,我想将令牌用作会话标识符,并将会话值保留在后端,例如:

 nJwt.verify(socket.handshake.query.token, app.get("jwt.secret"), (err, decoded) => { if (err) return; // Since we verified token, read token's session data from backend }); 

有没有这样做的例子?

PS。 我使用Redis,所以我可以通过Redis设置/获取值,但是我觉得这是不好的做法,因为我会自己开发整个会话。

为了唯一标识您的令牌,您可以将整个令牌string作为标识符,尽pipe这样做太不合理,因为它太长而且不方便。 相反,jwt已经为此目的制定了标准: jti

所以生成你的标记是这样的:

 var claims = { iss: process.env.DOMAIN, jti: yourGenerateUniqueIdFunction(); }; 

JWTvalidation之后,您将获得jti值。 在后端,你可以像这样build立Session K / V Store:

 [jti].[keyName] -> [value] 

访问K / V这样​​的东西:

 Session.get('3452345.email') //doge@doge.com 

另一种方式如何实现你想要的只是启用默认会话机制( https://github.com/expressjs/session ),然后使用https://github.com/tj/connect-redis来存储会话在你的Redis商店。 通过这种方式,您可以轻松读取和写入req.session,并将其备份到configuration的Redis存储中。