使用socket.io和express-session时,会在每次页面加载时生成新的会话ID

时间:2015-09-16 21:00:44

标签: javascript node.js session express socket.io

我正在尝试在用户" PHP应用程序"之间建立通信。以及在Socket.io环境中运行的Node.js服务器。

每次重新加载php页面时,io cookie值都会获得一个新的sessionID值。这样做的问题是我在每个页面加载请求上都失去了用户的会话,这阻止了我保持数据会话数据的活动。

我可以做些什么来确保每次重新加载页面时io cookie值都不会生成新的sessionID?

这是我的服务器实现

const env = require('./config');
const sess = require('./sessions');
const app = require('express')();
const https = require('https');
const fs = require('fs');
const session = require('express-session');
const RedisStore = require("connect-redis")(session);
const cookie = require('cookie');
const server = https.createServer(
    {
        key: fs.readFileSync('certs/key.pem'),
        cert: fs.readFileSync('certs/cert.pem')
    }, function (req, res){
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
    }
).listen(env.socket.port, env.socket.host, function () {

    console.log('\033[2J');
    console.log('Websocket is running at http://%s:%s', server.address().address, server.address().port);
});

const io = require('socket.io')(server);

const sessionMiddleware = session({
    store: new RedisStore({
        host: env.redis.host,
        port: env.redis.port
    }),
    secret: env.session.secret,
    name: env.session.name,
    rolling: false,
    resave: true,
    saveUninitialized: true,
    cookie: {
         maxAge: null
    }
});

var clients = {};

io.use(function(socket, next) {
    sessionMiddleware(socket.request, socket.request.res, next);
});

app.use(sessionMiddleware);


app.get('/', function (req, res) {
    res.send('Welcome!');
});

io.on('connection', function (socket) {

    var origin = socket.request.headers.origin || '';
    var myIP = socket.request.socket.remoteAddress || '';
    var socketId = socket.id;
    var session_id = '';
    var authorized = false;
    var req = socket.request;


    //console.log(socket.request);
    console.log('SessionID: ' + socket.request.sessionID)

    if (!originIsAllowed(origin)) {
        // Make sure we only accept requests from an allowed origin
        socket.destroy();
        console.log((new Date()) + ' Connection from origin ' + origin + ' rejected.');
        return false;
    }

    if(req.sessionID){
        session_id = req.sessionID;
    }

    if(req.session.authorized){
        authorized = req.session.authorized;
    }

    //console.log(socket.handshake.headers);
    socket.on('connectMe', function(msg){

        if(!msg || !msg.tokenId || msg.tokenId == 'undefined'){
            console.log('SessionId was not found!');
            return false;
        }

        if(!myIP){
            console.log('Could not find client\'s IP Address');
            return false;
        }

        var userCons = clients[session_id] || [];

        if(userCons.indexOf(socketId) == -1){
            userCons.push(socketId);
        }

        clients[session_id] = userCons;

        console.log(clients);

        var uncoded_token = new Buffer(msg.tokenId, 'base64');

        //autherize the user only once - until the session is terminated
        if( !authorized && sess.handleSession(uncoded_token, myIP, env.session.duration) ){
            authorized = true;
            session.authorized = authorized;
        }

    });

    socket.on('chat', function(msg){
        //only autherized users can chat
        if( session.authorized ){
            console.log('Chat Message: ' + msg);
            socket.emit('chat', { message: msg });
        }

    });


    socket.on('disconnect', function(msg){
        console.log('Closing sessionID: ' + session_id);
        var userCons = clients[session_id] || [];

        var index = userCons.indexOf(socketId);

        if(index > -1){
            userCons.splice(index, 1);
            console.log('Removed Disconnect Message: ' + msg);
        } else {
            console.log('Disconnect Message: ' + msg);
        }

    }); 

    socket.on('error', function(msg){
        console.log('Error Message: ' + msg);
    }); 

});


function originIsAllowed(origin) {
    // put logic here to detect whether the specified origin is allowed.
        var allowed = env.session.allowedOrigins || []

        if(allowed.indexOf(origin) >= 0){
            return true;
        }

    return false;
}

这是我的客户代码

<script>

    $(function(){
        var socket = io.connect('https://10.0.4.18:8020', {secure: true, port: 8020});

        socket.emit('connectMe', { 'tokenId' : 'dm5tczBpLVk5Qk10bmpvLUZndmIzQU56ZlpTNTVmOWQxNjgwMmY4NA==' });

       //When the "send" button is clicked
        $('#f').click(function(e){
            e.preventDefault();
            var message = $('#m').val().trim();
            if( message  == ''){
                return false;
            }

            socket.emit('chat', message);
            $('#m').val('');
        });

        socket.on('chat', function(msg){
            $('#messages').append($('<li>').text(msg));
        });

    });

</script>

0 个答案:

没有答案