我需要一种方法来保护我的WebSockets。
像onConnect->checkcredentials if(credentials===false){die()}
但是将自己的凭据数据发送到服务器。如果没有令牌或饼干,我怎么能意识到呢?如果没有,是否有任何其他解决方案可以安全地进行实时通信?
答案 0 :(得分:2)
我需要一种方法来保护我的WebSockets。
使用此方法,只有知道参数和密码的客户端才能通过握手网关(中间件)
[编辑>使用新的UIScrollView
,it has fixed an issue regarding the query ]
@ 客户:
socket.io 2.0
@ 服务器:
io('http://216.157.91.131:8080/', { query: "s=$€CR€T" });
在这种情况下,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
});
对所有人来说都是相同的,可以是特定的数据库检查。
如果他们在timeOut中没有提供正确的凭据,您还可以连接断开连接(计时器踢)的客户端。 示例:
theSecret
如果客户端在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!"); }
}
中指定的时间内没有 auth ,则会断开连接。
我还在示例中包含了一个针对唯一授权客户端的小型演示(请求在unauthed =断开连接时)
您也可以在authed后使它们加入特定的私有名称空间,这样所有客户端的全局广播都不会包含未经过发送的侦听器。
祝你好运,希望它有所帮助。注意:
还有其他安全实时通信的解决方案吗?
要回答这个问题,您首先需要考虑这些威胁。有许多安全方法,例如,使用socket.io over SSL。
我提到的解决方案是为了避免未经授权的客户保持在线状态并访问事件/资源等...