Socket.io - 为私人消息实现用户-套接字关联映射

Lig*_*low 5 javascript sockets websocket node.js socket.io

我正在尝试使用 socket.io 创建一个私人消息系统

为了将用户与其套接字相关联,大多数站点都建议如下:

var people = {};

client.on('connection', function(socket) {

    //join the server
    socket.on('add user', function(user_id) {
        //create user-socket map
        people[user_id] = socket.id;
    });

});
Run Code Online (Sandbox Code Playgroud)

在我看来,上面代码的问题在于它user_id是从客户端发送的,所以如果用户以某种方式修改它并发送另一个user_id,就会发生模拟。

另外,我无法访问req.user._idclient.on('connection'...所以我应该如何user_id从服务器端获取?我正在使用 node.js、passport 和 express。

Ana*_*d S 4

我将使用jsonwebtokensocketio-jwt模块来解决这个安全问题。

服务器:

var secret = 'shhhhhh';
app.get('/getJWT', function(req, res) {
    /* Do your authentication here using header and get the userId */
    var userId = 'someId';
    var jwt = require('jsonwebtoken');
    var token = jwt.sign({ 'userId': userId }, secret);
    res.json({
        token: token
    });
});

var socketioJwt = require('socketio-jwt');
io.use(socketioJwt.authorize({
    secret: secret,
    handshake: true
}));

io.sockets.on('connection', function (socket) {
    var userId = socket.decoded_token.userId;
    /* your logic */
Run Code Online (Sandbox Code Playgroud)

客户:

var token = "token you got from the /getJWT"
var c = io.connect('http://localhost:3000/', { query: "token=" + token });
Run Code Online (Sandbox Code Playgroud)

由于令牌是用秘密编码的,因此客户端无法更改和发送它。

请参阅本文以了解为什么这样做更好。