简体   繁体   English

无法从带有Socket.IO的cookie获取Express会话ID

[英]Can't get Express session ID from cookies w/ Socket.IO

I have a typical web application in Node that is utilizing the Express framework and the session middleware. 我在Node中有一个典型的Web应用程序,它使用Express框架和会话中间件。 I am also using Socket.io for certain dynamic parts of my application (currently, this is a chat mechanism, but that's tangential). 我也在为我的应用程序的某些动态部分使用Socket.io(目前,这是一个聊天机制,但这是切向的)。 I've been able to successfully set up sessions and socket.io on their own, but would like to combine them (EG: to associate socket chat messages with user accounts without hitting the database). 我已经能够自己成功地设置会话和socket.io,但是想要将它们组合起来(EG:将套接字聊天消息与用户帐户相关联而不会访问数据库)。

It should be noted (and I can see this being a possible issue point), I am running two express servers on different ports: one for regular HTTP traffic, and one for HTTPS traffic. 应该注意(我可以看到这是一个可能的问题点),我在不同的端口上运行两个快速服务器:一个用于常规HTTP流量,一个用于HTTPS流量。 However, I am having both servers undergo an idential configuration and share the same session store. 但是,我让两台服务器都经过了一个完美配置并共享同一个会话存储。 Sessions do persist for me between http and https pages. http和https页面之间的会话确实存在。 The session is being set initially via a page served from HTTPS and the socket.io page is vanilla HTTP. 最初通过HTTPS提供的页面设置会话,socket.io页面是vanilla HTTP。

I'm following the guide located here to achieve what I am looking for regarding integrating socket.io and sessions. 我正在按照这里的指南来实现我正在寻找的有关集成socket.io和会话的内容。 However, within the authorization function, data.headers.cookie is never set, despite the session-based portions of my application working as expected. 但是,在授权功能中,尽管我的应用程序的基于会话的部分按预期工作,但从未设置data.headers.cookie。 What's more strange is that after setting a session, if I do a console.log(document.cookie) from within the browser, I get an empty string, but when I look at my cookies with the Firefox developer toolbar, there is an SID cookie for both express and connect. 更奇怪的是,在设置会话后,如果我从浏览器中执行console.log(document.cookie) ,我会得到一个空字符串,但是当我使用Firefox开发人员工具栏查看我的cookie时,会有一个SID用于表达和连接的cookie。

Here is the relevant portion of the server code: 以下是服务器代码的相关部分:

var config = {
    ip          : "127.0.0.1",
    httpPort    : 2031,
    httpsPort   : 2032
};

var utils       = require("./utils"),
    express     = require('express'),
    fs          = require('fs'),
    parseCookie = require('./node_modules/express/node_modules/connect').utils.parseCookie,
    routes      = require('./routes')(config); 

var httpsOpts = {
    key : fs.readFileSync("cert/server-key.pem").toString(),
    cert: fs.readFileSync("cert/server-cert.pem").toString()
 };

var app             = express.createServer(),
    https           = express.createServer(httpsOpts),
    io              = require("socket.io").listen(app, { log: false}),
    helpers         = require("./helpers.js"),
    session         = new express.session.MemoryStore(),
    sessionConfig   = express.session({
        store   : session,
        secret  : 'secret',
        key     : 'express.sid',
        cookie  : {maxAge : 60 * 60 * 1000}
    }); //share this across http and https

configServer(app);
configServer(https);

//get SID for using sessions with sockets
io.set('authorization', function(data, accept){
    if(data.headers.cookie){
        data.cookie = parseCookie(data.headers.cookie);
        data.sessionID = data.cookie['express.sid'];
    } else {
        return accept("No cookie transmitted", false);
    }

    accept(null, true);
});

io.sockets.on('connection', function(socket){
    //pull out session information in here
});

function configServer(server) {
    server.configure(function(){
        server.dynamicHelpers(helpers.dynamicHelpers);
        server.helpers(helpers.staticHelpers);
        server.set('view options', { layout: false });
        server.set('view engine', 'mustache');
        server.set('views', __dirname + '/views');
        server.register(".mustache", require('stache'));
        server.use(express.static(__dirname + '/public'));
        server.use(express.bodyParser());
        server.use(express.cookieParser());
        server.use(sessionConfig);
    });
}

And here's the relevant code on the client: 这是客户端上的相关代码:

<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var socket = io.connect('http://127.0.0.1'); //make sure this isn't localhost!
        socket.on('server', function(data){
            //socket logic is here
        });
    }
</script>

UPDATE UPDATE

Even after setting a cookie manually (and not just a session variable) in the route for the page that is using SocketIO, the cookies portion of the request is still absent. 即使在使用SocketIO的页面的路由中手动设置cookie(而不仅仅是会话变量)之后,请求的cookie部分仍然不存在。

I never would have thought of this until told to look at the initialization on the client side. 在被告知要查看客户端的初始化之前,我从未想过这个。 I changed the address from localhost to the explicit IP (127.0.0.1) and the cookies are now being sent with the header in Socket.IO. 我将地址从localhost更改为显式IP(127.0.0.1),现在正在使用Socket.IO中的标头发送cookie。 I'm not sure if this is obvious or not, as I assumed localhost was being mapped to 127.0.0.1 anyway. 我不确定这是否显而易见,因为我认为localhost无论如何都被映射到127.0.0.1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM