node.jsmongodbsocket.io-1.0

How to implement socket.io authentication with bearer token in nodejs


How validate the incoming connections , how create private namespaces , before emitting any event to client how to validate the client role every socket


Solution

  • you can set "authorization" to your socket connection .The client sends the auth token through the handshake data's query parameter.Which I then validate using the socketAuth method. Have a look at the code sample below and let me know if it helps

    /**
     * Check authorization Here
     */
    ioSocket.set('authorization', function (handshakeData, callback) {
        console.log("Inside Auth Handshake");
        console.log(handshakeData._query);
    
        if (handshakeData._query && handshakeData._query.token) {
            var token = handshakeData._query.token;
            socketAuth(token, function (err, res) {
                if (err) {
                    console.log(err);
                    console.log("** Socket Authentication Done :" + false);
                    return callback(null, false);
                } else {
                    console.log(" *** Socket Authentication Done :" + res);
                    return callback(null, res);
                }
            });
        } else {
            console.log("*Socket Authentication connection: false , Done :" + false);
            return callback(null, false);
        }
    
    });
    
    socketAuth = function (token, callback) {
        verifyToken(token, function (err, res) {  // method to get the user of this token from the DB and validate the connection.
            if (err) {
                return callback(true, false);
            } else {
                return callback(null, res);
            }
        });
    }
    

    A client side example of how to connect to socket with a auth token.

    var socket = require('socket.io-client')('<SERVER IP>/?token=9a05f8279436549875d1c2cd');
    
    socket.on('connect', function () { console.log("socket connected"); });
    socket.emit('event_name',{"message":"hello"});