Socket.io - Implementing a user-socket association map for private messaging

前端 未结 4 1939
既然无缘
既然无缘 2021-02-09 23:23

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:

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-10 00:20

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

    Server:

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

    Client:

    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.

提交回复
热议问题