socket.io 和 express 4 个会话 [英] socket.io and express 4 sessions

查看:29
本文介绍了socket.io 和 express 4 个会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 socket.io 应用程序中访问 express 4 会话.我对 Node 有点陌生,但在实现此功能时遇到了一些麻烦.

I would like to access the express 4 session in my socket.io app. I'm kind of new with Node and I have some troubles implementing this functionality.

我发现了一个允许访问 express 4 会话的 npm 模块:https://www.npmjs.org/package/session.socket.io-express4https://github.com/eiriklv/session.socket.io

I found a npm module that allows access to the express 4 session : https://www.npmjs.org/package/session.socket.io-express4 or https://github.com/eiriklv/session.socket.io

如果你看看我下面的 app.js 代码,我在 sessionsessionStorecookieParser 设置中做错了什么,因为我就是无法让这个模块工作.

If you look at my app.js code below, I'm doing something wrong in the session, sessionStore or cookieParser setup because I just can't get this module working.

// init modules
var express = require('express');
var helmet = require('helmet');
var fs = require('fs');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var memoryStore = session.MemoryStore;
var app = express();

// set variables
var options = {
  key: fs.readFileSync('./openssl_keys/server_key.pem'),
  cert: fs.readFileSync('./openssl_keys/server_cert.pem')
};
var cookieSecret = "secret phrase";
var sessionStore = new memoryStore();

app.set('env', process.env.NODE_ENV || 'development');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser(cookieSecret));
app.use(session({
    secret: cookieSecret,
    cookie: {httpOnly: true, secure: true},
    store: sessionStore
}));
app.use(function(req, res, next){
    res.locals.session = req.session;
    next();

});
app.use(express.static(path.join(__dirname, 'public')));

//routes
require('./routes/index')(app);
require('./routes/test')(app);


// starting http and https servers
var http = require('http').createServer(app).listen(8000, function(){
    console.log("http server listening on port 8000");
});
var https = require('https').createServer(options, app).listen(8080, function(){
    console.log("https server listening on port 8080"); 
});

// starting socket.io & session handler
var serverIO = require('socket.io').listen(https);
var SessionSockets  = require('session.socket.io-express4');
var io = new SessionSockets(serverIO, sessionStore, cookieParser);

io.on('connection', function(err, socket, session){
    if(err) throw err;
    console.log("connected");
    //console.log(session);
    socket.on('clientMessage', function(content) {
        console.log("received client message")
        console.log(content);
    });

});

module.exports = app;

我尝试了多种可能性,例如:

I tried multiples possibilities like :

  • 禁用 https 服务器.
  • 使用秘密短语设置 cookieParser 对象(因此它实际上"将秘密短语导出到 io = new SessionSockets(serverIO, sessionStore, cookieParser);)
  • 使用最少的 cookie 选项.
  • Disabling https server.
  • Setting up a cookieParser object with secret phrase (so it "actually" exports the secret phrase to io = new SessionSockets(serverIO, sessionStore, cookieParser);)
  • Using minimal cookie options.

无论如何,我对此有点迷茫,欢迎提出任何建议/批评.

Anyway I'm a bit lost with this, any suggestions/critics are welcome.

更新

好的,经过多次尝试,我想我可以让它工作!

Ok so after numerous tries I think I could get it work!

问题在于 cookieParser 初始化,正确的方法似乎是:

The problem is with the cookieParser initialization which the correct way seems to be :

var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.use(session({
    secret: "secret phrase",
    cookie: {httpOnly: true, secure: true},
    store: sessionStore
}));
var io = new SessionSockets(serverIO, sessionStore, cookieParser());

请注意,如果我使用 var io = new SessionSockets(serverIO, sessionStore, cookieParser);(而不是 cookieParser()),则它不起作用.这似乎是问题所在.

Notice that if I use var io = new SessionSockets(serverIO, sessionStore, cookieParser); (instead of cookieParser()) then it ain't working. That seems to be the problem.

如果我使用:

app.use(cookieParser("secret phrase"));
app.use(session({
    secret: "secret phrase",
    cookie: {httpOnly: true, secure: true},
    store: sessionStore
}));
var io = new SessionSockets(serverIO, sessionStore, cookieParser("secret phrase"));

然后模块崩溃并显示以下错误消息:

then the module crashes with the following error message :

session.socket.io-express4/session.socket.io.js:41
ake.signedCookies[key] = handshake.signedCookies[key].match(/:(.*)./).pop();
                                                                        ^
TypeError: Cannot call method 'pop' of null

但是如果我使用:

app.use(cookieParser("secret phrase"));
app.use(session({
    secret: "secret phrase",
    cookie: {httpOnly: true, secure: true},
    store: sessionStore
}));
var io = new SessionSockets(serverIO, sessionStore, cookieParser());

那么一切看起来都很好.

Then everything looks fine.

现在在 cookie 解析器文档中 (https://github.com/expressjs/cookie-parser) 意思是你可以传递一个密钥来让 cookie 签名.这是我想要的东西.

Now in the cookie-parser doc (https://github.com/expressjs/cookie-parser) it's saying you can pass a secret key to get the cookies signed. Which is something I'd like to have.

有人能解释一下 cookie-parser 秘密短语和会话秘密短语的关系吗?它们必须相同/不同吗?

Could someone explain me the relation with the cookie-parser secret phrase and the session secret phrase ? Do they have to be the same/different ?

推荐答案

以下是我针对以下环境的解决方案:

Here's my solution for the following environment:

  • 表达 4.2.0
  • socket.io 1.1.0
  • cookie 解析器 1.0.1
  • cookie 会话 1.0.2

代码:

var cookieParser = require('cookie-parser')();
var session = require('cookie-session')({ secret: 'secret' };

...

app.use(cookieParser);
app.use(session);

...

io.use(function(socket, next) {
    var req = socket.handshake;
    var res = {};
    cookieParser(req, res, function(err) {
        if (err) return next(err);
        session(req, res, next);
    });
});

然后就可以通过socket的握手访问会话了:

Then you can access the session from the socket's handshake:

io.on('connection', function (socket) {
    console.log("Session: ", socket.handshake.session);
});

对于想知道它如何/为什么起作用的人:

For people wondering how/why this works:

  • 我们通过 cookie 解析器发送 handshake 请求,以便 cookie 可用
  • 然后我们通过会话中间件发送handshake,就好像它是一个正常的请求
  • 中间件将session附加到请求
  • 我们使用 handshake 是因为就所有意图和目的而言,这是一个正常的请求,解析器和会话中间件可以正确处理它.这就是为什么你必须通过 handshake
  • 访问 session
  • We send the handshake request through the cookie parser so that cookies are available
  • Then we send the handshake through session middleware as if its a normal request
  • The middleware attaches session to the request
  • We use handshake because for all intents and purposes, it is a normal request, and the parser and session middleware can deal with it properly. This is why you must access the session through the handshake

这篇关于socket.io 和 express 4 个会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆