javascript - Socket.io 重新授权

标签 javascript node.js socket.io

我正在尝试将 cookie 传回服务器,在授权发生很久之后。原因是我想检查在套接字打开一段时间后用户是否仍然登录。有没有办法用 socket.io 做到这一点?也许通过再次强制授权;这可能吗?

最佳答案

您应该能够通过启用 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 以特定时间间隔执行检查。

关于javascript - Socket.io 重新授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13279676/

相关文章:

node.js - 尝试注册 bower.json 文件时出现 EMALFORMED 错误

mysql - Node Mysql 序列化 'ERR_BUFFER_OUT_OF_BOUNDS'

javascript - 删除 Angular-Node-Passport 身份验证中的浏览器历史记录

Node.js Express 4.11.2 & socket.io 出现错误?EIO=3&transport=polling&t=

javascript - 使用 jquery sort() 函数对元素进行排序在 webkit 上失败

javascript - 将没有 id 的值写入 td?

javascript - 是否可以将 PHP 代码嵌入到 HTML 标记的类或名称属性中?

javascript - 为什么 Javascript 对象不更新字段?

node.js - Socket IO 无限循环超过 1000 个连接

node.js - 使用 Node 连接到 MongoDB 服务器在本地主机上没有响应