node.js - Authentication in Socket.io -
i'm going try authenticate connection on socket.io.
currently, user first authenticated via rest api, then, send user jsonwebtoken
authenticated user's username. after open connection between client , server, plan temporarily delete socket list of connected sockets prevent receiving , sending of data between server while carry out auth.
in auth, verify token , if token valid re-add socket's id list of connected sockets. problem first part doesn't work. can't seem delete socket list.
to test did following.
io.on('connection', function(socket){ //temp delete socket delete io.sockets.connected[socket.id]; console.log(io.sockets.connected); socket.emit("test"); });
as can see delete socket , emit test event see if socket still open. message received client when shouldn't be.
does know why occurs?
try using disconnect method socket object, this:
io.on('connection', function(socket){ //temp delete socket socket.disconnect(); console.log(io.sockets.connected); socket.emit("test"); });
update:
for example if http server gives client token:
app.post('/api/users', function (req, res) { var user = { username: req.body.username }; var token = jwt.sign(user, secret, {expiresinminutes: 30}); res.json({token: token}); });
then can reuse token authenticate websocket connections.
the token sending code client (html file) be:
socket = io.connect('http://localhost:4000', { query: 'token=' + validtoken, forcenew: true });
and socketio authorization code in server(socketio) be:
// here being used socketio middleware validate // token has been sent // , if token valid, io.on(connection, ..) statement below executed // socket connected websocket server. io.use(require('socketio-jwt').authorize({ secret: secret, handshake: true })); // if token not valid, error triggered client // socket won't connected websocket server. io.on('connection', function (socket) { console.log('socket connected'); });
note secret used on express generate token, same token being used on validation token @ socketio middleware.
i have created example can see how kind of validation works, source code here: https://gist.github.com/wilsonbalderrama/a2fa66b4d2b6eca05a5d
copy them in folder , run server.js node , access html file browser @ url: http://localhost:4000
but first install modules: socket.io, express, socketio-jwt, jsonwebtoken
Comments
Post a Comment