我需要一种方法来保护我的WebSockets。
有点像onConnect->checkcredentials if(credentials===false){die()}
但是有了自己的凭证数据才能发送到服务器。如果没有令牌和饼干,我怎么能意识到这一点?如果没有,是否有其他解决方案可以安全地进行实时通信?
发布于 2017-08-04 17:27:01
我需要一种方法来保护我的WebSockets。
解决方案:套接字握手查询
使用这种方法,只有知道参数和秘密的客户端才能通过握手网关(中间件)。
[编辑:使用新的socket.io 2.0,它已经解决了一个有关查询的问题。 ]
@ client:
io('http://216.157.91.131:8080/', { query: "s=$€CR€T" });@ server:
var theSecret = "S€CR€T";
io.use(function(socket, next) {
var handshakeSecret = socket.request._query['s'];
console.log("middleware:", handshakeSecret);
try{
if(handshakeSecret=theSecret){next();}else{socket.disconnect();}
}catch(e){socket.disconnect();} //prevent error - crash
});在这种情况下,theSecret对于所有的人来说都是一样的,可以是一个特定的签入数据库。
解决方案:8月或GTFO!(踢)
如果客户端没有在timeOut中提供正确的凭据,您也可以终止连接到断开连接(timer踢)的客户端。例子:
const SOCKET_AUTH_TIMEOUT = 120000; //2 minutes in ms
io.on('connection', function(socket){
//.: ALL SOCKET CONNECTIONS :.
console.log("[+] (unauthorized) client connected : "+socket.id);
//begin doom countdown...
socket.doom = setTimeout(KickSocketClient.bind(null, socket.id), SOCKET_AUTH_TIMEOUT);
//warn this client : (example)
//@ client : 'You got '+TimeoutInMinutes+' minutes to authorize before being kicked.'
socket.emit('auth_required', SOCKET_AUTH_TIMEOUT);
//.: Handle Authorization :.
socket.on('auth',function(authRequest){
/* your logic to verify the incoming authRequest goes here, for example :*/
if(DATABASE[authRequest.user]){ //user exists in imaginary in-memory database
if(DATABASE[authRequest.user].password == authRequest.password){ //correct password, success!
socket.emit('authed', DATABASE[authRequest.user]); //maybe return user data
socket.authed = true; //set this socket client as authorized (useful for future requests)
//now clear the timeout of d00m! (prevent the disconnection, now the client is authed)
clearTimeout(socket.doom);
}else{socket.emit('error','credentials');}
}else{socket.emit('error','credentials');}
});
//.: Handle Disconnections :.
socket.on('disconnect', function(){
if(socket.authed){console.log("[+] client disconnected : "+socket.id);}
else{console.log("[+] (unauthorized) client disconnected : "+socket.id);}
});
//.: Only for Authorized Clients :.
socket.on('secret', function(){
if(socket.authed){
console.log("[o] client : "+socket.id+" requested the secret");
socket.emit('return','the secret to life'); //here you go!
}else{socket.disconnect();} // disconnect the unauthorized client
});
});
function KickSocketClient(sid){
if (io.sockets.connected[sid]) {
console.log("[kick] client ("+sid+") : unauthorized status for too long");
io.sockets.connected[sid].disconnect();
}else{ console.log("<!> : [kick] client ("+sid+") not found!"); }
}如果客户端没有在中指定的时间内使用,那么它将被断开连接。
我还在示例中包括了一个仅授权客户端的小型演示(请求未创建=断开连接)
您还可以让它们加入特定的私有命名空间,这样所有客户端的全局广播都不包括未创建的侦听器。
祝你好运,希望能帮上忙。
注:
是否有任何其他解决方案,以确保实时通信安全?
要回答这个问题,你需要先考虑到威胁。有许多安全的方法,例如,在SSL上使用socket.io。
我提到的解决方案,是为了避免未经授权的客户停留在网上,并访问事件/资源/等等。
https://stackoverflow.com/questions/45403102
复制相似问题