2012-11-07 65 views
1

我試圖在授權發生後很長時間內將cookie傳回服務器。原因是我想檢查用戶是否在套接字打開一段時間後仍然登錄。有沒有辦法與socket.io做到這一點?也許再次強制授權;這可能嗎?Socket.io重新授權

回答

2

您應該可以通過啓用socket.io授權來完成該操作。一旦啓用,它將在socket.io連接時調用提供的函數。

這是我剛纔使用的一些代碼,應該讓你開始。

var connect = require('connect'); 

// these should be the same as you use for setting the cookie 
var sessionKey = "yourSessionKey"; 
var sessionSecret = "yourSessionSecret"; 

socketIO.set('authorization', function (data, accept) { 
    // check if there's a cookie header 
    if (data.headers.cookie) { 
     // if there is, parse the cookie 
     data.cookie = connect.utils.parseSignedCookies(cookie.parse(decodeURIComponent(data.headers.cookie)), sessionSecret); 
     if (!data.cookie[sessionKey]) return accept('No cookie value for session key ' + sessionKey, false); 
     var parts = data.cookie[sessionKey].split('.'); 
     data.sessionId = parts[0]; 

     // at this point you would check if the user has been authenticated 
     // by using the session id as key. You could store such a reference 
     // in redis after the user logged in for example. 

     // you might want to set the userid on `data` so that it is accessible 
     // through the `socket.handshake` object later on 
     data.userid = username; 

     // accept the incoming connection 
     return accept(null, true); 
    } else { 
     // if there isn't, turn down the connection with a message 
     // and leave the function. 
     return accept('No cookie transmitted.', false); 
    } 
}); 

一旦設定data屬性(例如,在上面的例子中data.userid)可以通過經由socket.handshake對象訪問它們。例如:

io.sockets.on('connection', function (socket) { 
    var userId = socket.handshake.userid; 

    socket.on('reauthorize-user', function(){ 
     // check the user status using the userId then emit a socket event back 
     // to the client with the result 
     socket.emit('reauthorization-result', isAuthorized); 
    }); 
}); 

在客戶端,你將只發出reauthorize-user事件,並聽取了reauthorization-result事件。你顯然可以有一個setTimeout在特定的時間間隔內執行檢查。

+0

嘿,謝謝你,但我想在套接字連接後運行授權。 –

+0

我明白了。您可能仍然需要執行授權步驟才能獲取socket.handshake對象上的用戶標識。一旦你有了,你應該能夠使用標準套接字事件來傳達用戶狀態。不知道是否有更簡單的方法來做到這一點。我更新了答案,以包含使用握手對象。 – JWK

+0

結合這個答案和[這個鏈接](https://github.com/DanielBaulig/sioe-demo/blob/master/app.js)我終於得到了它的工作。 – FelikZ