jfromaniello / passport.socketio

access passport.js authenticated user information from socket.io connection
655 stars 81 forks source link

No session found #143

Closed UnchartedBull closed 4 years ago

UnchartedBull commented 6 years ago

I can't figure out why I get No session found every time ... First of all I'm using express with CORS (it will be disabled later on), so I'm aware, that I do need to set session_id=cookie manually. Passport correctly works with Postman.

In my testscript the cookie isn't saved for an unknown reason, but I extract the session_id from the Chrome Debugger and insert it manually (I double checked the request in the debugger, that it is correctly attached). Here is the code for the test script:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
    <script>
        function readCookie(a) {
            var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
            return b ? b.pop() : '';
        }

        var settings = {
            "async": true,
            "crossDomain": true,
            "url": "url",
            "method": "POST",
            "headers": {
                "Content-Type": "application/x-www-form-urlencoded",
                "Cache-Control": "no-cache"
            },
            "data": {
                "email": "tmp",
                "password": "tmp"
            }
        };
        $.ajax(settings).done(function (data, textStatus, jqXHR) {
            if(jqXHR.status === 200) {
                 console.log("Logged in!")
            }
        });

        function startSocket() {
            id = $('#tmp').val();
            id = id.replace('s:','').split('.')[0];
            var socket = io.connect('url', {
                query: 'session_id=' + id
            });
        }

    </script>
</head>
<body>
    <input type="text" id="tmp" />
    <button onclick="startSocket()" value="connect">Connect</button>
</body>
</html>

And the code for initializing passport and passport.socketio:

// ======================= IMPORTS ======================= //
var express             = require('express');
var app                 = express();
var server              = require('http').Server(app);
var io                  = require('socket.io')(server);
var passport            = require('passport');
var passportSocketIo    = require('passport.socketio');
var session             = require('express-session');
var cookieParser        = require('cookie-parser');
var bodyParser          = require('body-parser');
var redisStore          = require('connect-redis')(session);
var config              = require('./config');
var logger              = require('./helper/logger')();
var port                = 8082;
var sessionStore        = new redisStore();

// ======================= LOAD CONFIG ======================= //
require('./config/passport')(passport, logger);

// ======================= SETUP EXPRESS ======================= //
app.enable("trust proxy");
app.use(express.static(__dirname + "/public"));
app.use(cookieParser());
app.use(session({
    cookieParser: sessionStore,
    secret: config.sessionSecret,
    key: "express.sid",
    sessionStore: sessionStore,
    resave: false,
    saveUninitialized: false,
    cookie: {
        httpOnly: false,
        maxAge: 12000000
    }
}));
app.use(require('cors')());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: 'true'}));
app.use(passport.initialize());
app.use(passport.session());
require('./routes')(app, passport, logger, config);

// ======================= SETUP SOCKET.IO ======================= //
io.use(passportSocketIo.authorize({
    cookieParser: cookieParser,
    key: "express.sid",
    secret: config.sessionSecret,
    store: sessionStore,
    success: onAuthorizationSuccess,
    fail: onAuthorizationFail
}));

function onAuthorizationSuccess(data, accept) {
    logger.debug("User connected!");
    logger.debug(data);
    accept();
}

function onAuthorizationFail(data, message, error, accept) {
    logger.debug("Client tried to connect. Rejected because of: " + message);
    return accept(new Error(message));
}

io.on("connection", function (socket) {
    logger.debug("A user connected!");
});

// ======================= START SERVER ======================= //
server.listen(port, function(err) {
    if (err) {
        logger.error("Error while trying to setup Express: " + err);
    } else {
        logger.info("Server listening on port " + port);
    }
});
eerFun commented 6 years ago

replace 'localhost' with '127.0.0.1' in client connect method & your URL.

kyaryunha commented 3 years ago

@eerFun
Hi

I had the same problem and solved it the same way you said. Thanks for a good solution.

I wonder why the localhost does not work, and 127.0.0.1 should be done.

Can you tell me or give me a link to a related resource?