Connect.sid 始终未定义并且 req.sessionID 不断重置

poo*_*zko 3 cookies session redis node.js angularjs

我对 NodeJS/Express/Socket.IO 很陌生,并且使用 Socket.IO 通信制作了一个简单的石头剪刀布应用程序(在客户端我使用的是 AngularJS)。到目前为止,应用程序的那部分工作得很好。

但是,我开始致力于使用 Redis 实现会话,并偶然发现了一些问题。由于我这样做是为了学习,因此我决定使用套接字来制作应用程序的一部分(玩石头剪刀布游戏的整个实时部分),而另一部分则不需要真正的- 使用常规 REST 的时间组件(排行榜、查看其他人的个人资料等)。

我遇到的问题是 connect.sid cookie 从未在客户端上设置。我做了一个简单的checkSessionREST 调用来测试会话是否持续存在,但似乎不是。我在checkSession通话中还注意到,req.sessionID总是给我一个全新的 sessionID。现在,我不确定是否应该connect.sid手动创建,还是节点应该自动处理?如果我应该做,我该怎么做?“设置授权”回调也从不包含connect.sid握手对象中的cookie。

另外,从我在研究这个过程中读到的内容来看,在常规 REST (Express) 和 Socket.IO 之间共享会话可能有点麻烦。这是我的代码(我关闭了整个石头剪刀布逻辑以确保这不是导致问题的原因)。

package.json

{
  "name": "RPSLS.Node",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.5.1",
    "session": "0.1.0",
    "socket.io": "0.9.16",
    "redis": "0.10.2",
    "connect-redis": "1.4.7"
  }
}
Run Code Online (Sandbox Code Playgroud)

app.js

var express = require('express');
var parseCookie = express.cookieParser("megaultrasupersecret");

var http = require('http');
var path = require('path');
var io = require('socket.io');

var app = express();
var server = http.createServer(app);
var ioServer = io.listen(server);

var redis = require('redis');
var RedisStore = require('connect-redis')(express);

// Route dependencies
var sharedData = require('./shared/data')();
var routes = require('./routes');

// Enable CORS
var allowCrossDomain = function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://rpsls.local" || "http://localhost" || "http://127.0.0.1");
    res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    next();
}

// All environments
app.set('port', process.env.PORT || 7331);
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser("megaultrasupersecret"));
app.use(express.session({ store: new RedisStore({ client: redis.createClient() }), key: "connect.sid", secret: "megaultrasupersecret", cookie: { maxAge: 24 * 60 * 60 * 1000 } }));
app.use(allowCrossDomain);
app.use(app.router);

ioServer.configure(function () {
    ioServer.set('store', new io.RedisStore({
        redisPub: redis.createClient(),
        redisSub: redis.createClient(),
        redisClient: redis.createClient()
    }));

    ioServer.set('authorization', function (handshakeData, callback) {
        console.log(handshakeData.headers.cookie); // always returns undefined

        parseCookie(handshakeData, null, function (err) {
            // both always returns undefined
            console.log(handshakeData.signedCookies['connect.sid']);
            console.log(handshakeData.cookies['connect.sid']);
        });

        callback(null, true); // error first callback style 
    });
});

app.get("/", routes.index);
app.get("/checkSession", routes.checkSession);

ioServer.sockets.on('connection', function (socket) {
    // ... socket logic ... 
});

server.listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
});
Run Code Online (Sandbox Code Playgroud)

checkSession实施:

module.exports = function () {
    return {
        index: function (req, res) {
            res.send("RPSLS.Node API is online.");
        },
        checkSession: function (req, res) {
            console.log("----------- SESSION:   ");
            console.log(req.session);
            console.log("----------- Session ID:   " + req.sessionID); // always a brand new sessionID
            console.log("----------- Session UserName:   " + req.session.userName); // never gets persisted
            console.log("----------- Connect.sid:   " + req.cookies["connect.sid"]); // always undefined
            console.log("----------- REQ cookies:   "); 
            console.log(req.cookies); // sometimes outputs some _ga cookie (have no clue what it's for), but nothing else

            req.session.userName = "someUserName";
            req.session.save(function () {
                res.send("TEST");
            });
        }
    };
};
Run Code Online (Sandbox Code Playgroud)

它的console.log输出:

----------- SESSION (this is what gets stored in redis):
{ cookie:
   { path: '/',
     _expires: Mon May 26 2014 22:56:23 GMT+0200 (Central European Daylight Time),
     originalMaxAge: 86400000,
     httpOnly: true } }
----------- Session ID:   7KIjYzdqfyZFCjDDT4bE1P5a
----------- Session UserName:   undefined
----------- Connect.sid:   undefined
----------- REQ cookies:  {}
Run Code Online (Sandbox Code Playgroud)

Angular HTTP 调用:

this.checkSession = function () {
    $http.get('http://localhost:7331/checkSession')
        .success(function (userName) {
            console.log(userName);
        });
};
Run Code Online (Sandbox Code Playgroud)

以下是来自 Redis 的一些密钥,以确认它正在工作(我还在应用程序的其他部分成功地将一些其他数据保存到 Redis,但认为这与此处无关):

127.0.0.1:6379> keys *
sess:Fe8ND2riR4jQEtCEmhYKi4hS
sess:WGLNkth7HW2PtR2AG4noId8Q
sess:Ph0aUwRWEtawEWxIrqVQj3Us
sess:RzLVnaLV8BPZqUsjCCzV9RCn
sess:ZfmMcGUyFf957IsVc1gkbXKb
sess:6zdD3PStbx1EmFtHjoxmVGkr
sess:QNyHy4PUNE21fBrgmjiyjNkq
Run Code Online (Sandbox Code Playgroud)

我在 DevTools 中注意到的另一件事是名为 的响应 cookie connect.sid,其中包含会话 id 和散列密钥。此会话 ID 始终是我进入的新 ID checkSession。我应该手动在客户端上设置它,还是应该开箱即用?

在此处输入图片说明

这是来自响应头:

Set-Cookie:connect.sid=s%3AvMXrIBuaheA7ZBkxql51HQfO.67KqBFY4DVS4rQ50jv2B6bn4V6LeLMpdMxcpP6P%2FXIc;
Path=/; Expires=Mon, 26 May 2014 21:19:05 GMT; HttpOnly
Run Code Online (Sandbox Code Playgroud)

我花了很多时间试图弄清楚这一点,但我对为什么这不起作用一无所知。一切都在本地主机上运行。我不理解和做错了什么,我错过了什么?

edit1:根据mscdex的请求,console.dir(req.headers)输出以下内容:

{ host: 'localhost:7331',
  'user-agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0', accept: 'application/json, text/plain, */*',
  'accept-language': 'en-US,en;q=0.5',
  'accept-encoding': 'gzip, deflate',
  dnt: '1',
  referer: 'http://localhost:9000/',
  origin: 'http://localhost:9000',
  connection: 'keep-alive',
  'if-none-match': '"-286616648"',
  'cache-control': 'max-age=0' }
Run Code Online (Sandbox Code Playgroud)

edit2:如果它有任何重要性,NodeJS 应用程序正在运行localhost:7331,我尝试在localhost:9000(通过 grunt)127.0.0.1:9000rpsls.local(通过 MS IIS)上运行 AngularJS,结果相同。

msc*_*dex 6

尝试添加res.header("Access-Control-Allow-Credentials", "true");到您的allowCrossDomain中间件功能。您也可以考虑使用cors中间件,而不是自己处理 CORS。

然后修改您的角度get调用添加withCredentials: true请求配置:$http.get('http://localhost:7331/checkSession', { withCredentials: true })