1

承認が行われてからずっと後に、Cookieをサーバーに返送しようとしています。その理由は、ソケットがしばらく開いた後もユーザーがまだログインしているかどうかを確認したいからです。socket.ioでこれを行う方法はありますか?たぶん、承認を再度強制することによって。これは可能ですか?

4

1 に答える 1

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 を持つことができます。

于 2012-11-07T23:14:37.457 に答える