node.js - Using JWT tokens. Is there a better approach? -
i'm using jwt tokens via njwt package authenticate users socket.io using socket.io-jwt package.
more or less, code looks this. user sends post reques play/login via html form generate jwt token. then, socket.io client initializes using token.
/** * create express server. */ const app = express(); const http = require('http').server(app); const io = require('socket.io')(http); const socketiojwt = require('socketio-jwt'); app.set('jwt.secret', securerandom(256, { type: 'buffer' })); app.post('/play/login', (req, res) => { // validate user's req.body.email , req.body.password const claims = { iss: "http://app.dev", // url of service sub: "user-1", // uid of user in system scope: "game" }; const jwt = njwt.create(claims, app.get("jwt.secret")); const token = jwt.compact(); new cookies(req,res).set('access_token', token, { httponly: true, secure: process.env.environment === "production" }); tokenuserrelations[token] = req.body.email; res.json({ code: 200, token: token }); }); /** * add socket io auth middleware */ io.set('authorization', socketiojwt.authorize({ secret: app.get("jwt.secret"), handshake: true })); io.sockets.on('connection', function (socket) { socket.on('chat message', function (req) { io.emit("chat message emit", { email: tokenuserrelations[socket.handshake.query.token], msg: req.msg }); }); socket.on('debug', function (req) { io.emit("debug emit", { playersonline: object.keys(tokenuserrelations).length }); }); socket.on('disconnect', function (req) { delete tokenuserrelations[socket.handshake.query.token]; }); }); io.listen(app.get('socket.port'), () => { console.log('started! socket server listening on port %d in %s mode', app.get('socket.port'), app.get('env')); });
right now, works properly, in order track emails tokens, had this:
tokenuserrelations[token] = req.body.email;
so can relate user token points to.
i have feeling keeping token<->email relations in global object going cause me headaches in future, when tokens/cookies expires.
is there better way this? need know user jwt token points can business logic them.
thank you.
a token can contain information want, information encrypted along token.
what can encrypt user id in token, when receive request, decrypt token (which anyway done when verify it), , use user id normal.
this way, if token expire, new token have same user id, , code not impacted.
this did in 1 of web app, , worked fine. however, using official jwt module
Comments
Post a Comment