How validate the incoming connections , how create private namespaces , before emitting any event to client how to validate the client role every socket
Asked
Active
Viewed 7,922 times
1 Answers
2
you can set "authorization" to your socket connection .The client sends the auth token through the handshake data's query parameter.Which I then validate using the socketAuth method. Have a look at the code sample below and let me know if it helps
/**
* Check authorization Here
*/
ioSocket.set('authorization', function (handshakeData, callback) {
console.log("Inside Auth Handshake");
console.log(handshakeData._query);
if (handshakeData._query && handshakeData._query.token) {
var token = handshakeData._query.token;
socketAuth(token, function (err, res) {
if (err) {
console.log(err);
console.log("** Socket Authentication Done :" + false);
return callback(null, false);
} else {
console.log(" *** Socket Authentication Done :" + res);
return callback(null, res);
}
});
} else {
console.log("*Socket Authentication connection: false , Done :" + false);
return callback(null, false);
}
});
socketAuth = function (token, callback) {
verifyToken(token, function (err, res) { // method to get the user of this token from the DB and validate the connection.
if (err) {
return callback(true, false);
} else {
return callback(null, res);
}
});
}
A client side example of how to connect to socket with a auth token.
var socket = require('socket.io-client')('<SERVER IP>/?token=9a05f8279436549875d1c2cd');
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('event_name',{"message":"hello"});

Abana Clara
- 4,602
- 3
- 18
- 31

zoram
- 512
- 6
- 16
-
from the client side how to token, can provide any decimation link socket.io 1.0 io.set('authorization', cb) – HDK Aug 22 '15 at 11:36
-
Ho to emit event based on role – HDK Aug 22 '15 at 11:44
-
1For example in the sample code the "verifyToken" method would validate the user. You can use that method to decide what kind of user is trying to connect based on the token and emit accordingly through the emit event. see my edit. – zoram Aug 22 '15 at 11:52
-
Actually socket.io running in one instance another node api is running another instance , i am emiting events from api instance using socket.io.emiter . socket.io able to broadcast this emits to connected clients. but i want broad cast api events based one role ( owner cann sell events , member can listen limited events ) how can i achieve this any thing. how can Extend socket.io.adapter functionality – HDK Aug 22 '15 at 13:11
-
Can you provide a link to the documentation for `socket.io` `io.set('authorization', cb)`? – TheJKFever Mar 28 '17 at 23:17