Socket.IO Client Authentication in Express Application

I have an Express application that authenticates with Passport.js (with MongoDB backend).

Everything works fine, but now I am facing another problem:

I want to have some kind of "chat" function in my project, and for this I use Socket.IO (real-time message delivery).

The page checks that the user loads before loading, but this can still be circumvented.

I want the Socket.IO stream to be protected and authorized as well.

How to integrate Socket.IO chat system into my Passport.js based authentication?

+4
source share
2 answers

, , , cookie , . , .

var connect = require('express/node_modules/connect'),
    parseSignedCookie = connect.utils.parseSignedCookie,
    Cookie = require('express/node_modules/cookie'),
    store = YOUR_SESSION_STORE_INSTANCE, // i.e. redis-store, memory, or whatever 
    sessionKey = "YOUR SESSION KEY", // defaults to connect.sid
    sessionSecret = "YOUR SESSION SECRET";

var verifyCookie = function(data, callback){
    try{
        var cookie = Cookie.parse(data.headers.cookie);
        var sessionID = parseSignedCookie(cookie[sessionKey], sessionSecret);
        store.get(sessionID, callback);
    }catch(e){
        callback(e);
    }
};

// set up socket.io to validate cookies on an authorization request
// this assumes you've assigned your socket.io server to the io variable
io.configure(function(){
    io.set("authorization", function(handshake, accept){
        if(handshake.headers.cookie){
            verifyCookie(handshake, function(error, session){
                if(error || !session)
                    accept("Invalid authentication", false);
                else
                    accept(null, true);
            });
        }else{
            accept("Invalid authentication", false);
        }        
    });
});

100% , , , , , , , - , .

, . , , , , , , .

: , , cookie, , . , http://passportjs.org/guide/configure/:

passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});

2: - . , , , , redis. :

  • ( uuid) HTTP-. .
  • , redis , , - .
  • , socket.io URL- GET "" .
  • socket.io cookie, URL-, GET redis -, . redis , . redis , , - redis.

, socket.io . , , . , . . , , - .

WS WS. Sockjs cookie , socket.io sockjs.

+3

Express ver 4.x Socket.io ver 1.x, : http://mykospark.net/2014/07/authentication-with-socket-io-1-0-and-express-4-0

:

io.use(function(socket, next) {
    var handshake = socket.handshake;

    if (handshake.headers.cookie) {
        var req = {
            headers: {
                cookie: handshake.headers.cookie,
            }
        }

        cookieParser(config.session.secret)(req, null, function(err) {
            if (err) {
                return next(err);
            }
            var sessionID = req.signedCookies[config.session.name] ||
                            req.cookies[config.session.name];

            var sessionStore = new MongoStore({ db: global.db});
            sessionStore.get(sessionID, function (err, session) {
                if (err) {
                    return next(err);
                }

                // userData bellow is written once the Express session is created
                if (session && session.userData) { 
                    next();
                } else {
                    return next(new Error('Invalid Session'));
                }
            })
        });
    } else {
        next(new Error('Missing Cookies'));
    }
});
0

Source: https://habr.com/ru/post/1531381/


All Articles