Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Socketio authorization function in expressjs

Socketio authorization function in expressjs

Problem

im very noob and i have this Function to make the authorization.

io.set('authorization', function (handshakeData, accept) {
  // check if there's a cookie header
    if (req.session.user) {
        accept(null, true);
    }else{res.redirect("/");
        accept("NO AUTORIZADO!", false);

    }



    }); 
    next()
}); 

I want the user to be authenticated in the session before connecting with websockets

Problem courtesy of: Angel David Calderaro Pacciott

Solution

Assuming you are using express with redis as session store you can use the below code to validate the session.

var cookie = require('cookie'),
    connect = require('connect');

io.set('authorization', function (handshakeData, accept) {
if (handshakeData.headers.cookie) {
    handshakeData.cookie = cookie.parse(handshakeData.headers.cookie);
    handshakeData.sessionID = 'sess:'+connect.utils.parseSignedCookie(handshakeData.cookie['connect.sid'], config.session_secret);
    sredis.get(handshakeData.sessionID, function (err, session) {
        if (err || !session) {
            accept('could not load the session', false);
        } else {
            handshakeData.session = JSON.parse(session);
            accept(null, true);
        }
    });
} else {
    return accept('No cookie transmitted.', false);
}
});
Solution courtesy of: Chirag Jain

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Socketio authorization function in expressjs

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×