Socket.io - 为私人消息传递实现用户套接字关联映射 [英] Socket.io - Implementing a user-socket association map for private messaging

查看:112
本文介绍了Socket.io - 为私人消息传递实现用户套接字关联映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a private messaging system using socket.io

为了将用户与他们的套接字关联起来,大多数网站建议这样的事情:

In order to associate the users with their sockets, most sites are suggesting something like this:

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;
    });

});

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

In my opinion, the problem with the above code is that the user_id is sent from the client side, so if the user somehow modify it and send another user_id an impersonation will take place.

另外,我无法访问 client.on下的 req.user._id ('connection'... 所以我应该如何从服务器端获得 user_id ?我正在使用node.js,passport和快递。

Also, I can't access req.user._id under client.on('connection'... so how am I supposed to get the user_id from the server's side? I'm using node.js, passport and express.

推荐答案

我会使用 jsonwebtoken socketio-jwt 用于解决此安全问题的模块。

I would use jsonwebtoken and socketio-jwt modules for solving this security issue.

服务器:

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 */

客户:

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

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

As the token is encoded with a secret, client cannot change and send it.

请参阅文章,了解为什么这样更好。

Refer this article to know why this is better.

这篇关于Socket.io - 为私人消息传递实现用户套接字关联映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆