本文介绍了socket.io解析连接(> = 2.4.1)签名会话cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用最新版本的连接(截至2012-07-26),我发现以下方式可以从socket.io获取一个可以与connect-redis商店一起使用的会话ID。

With the latest version of connect (as of 2012-07-26), I've found the following way to get a session ID from socket.io that will work with a connect-redis store.

var express = require('express')
, routes = require('./routes')
, fs = require('fs')
, http = require('http')
, io = require('socket.io')
, redis = require('connect-redis')
, connect = require('express/node_modules/connect')
, parseSignedCookie = connect.utils.parseSignedCookie
, cookie = require('express/node_modules/cookie');

var secret = '...';
var rStore = new(require('connect-redis')(express));

//...

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

sio.set('authorization', function(data, accept) {
    if(data.headers.cookie) {
        data.cookie = cookie.parse(data.headers.cookie);
        data.sessionID = parseSignedCookie(data.cookie['connect.sid'], secret);
    } else {
        return accept('No cookie transmitted', false);
    }
    accept(null, true);
});

data.sessionID 可以稍后使用例如

sio.sockets.on('connection', function(socket) {
    console.log('New socket connection with ID: ' + socket.handshake.sessionID);
    rStore.get(socket.handshake.sessionID, function(err, session) {
        //...
    });
});

需要从express(connect,连接的实用程序和cookie模块)导入这么多像一个过于迂回的方式来获取解析连接的已签名Cookie所需的功能。有没有人找到另一种方式?

Having to import so many from express (connect, a utility of connect, and the cookie module) seems like an overly roundabout way of getting the functions needed to parse connect's signed cookies. Has anyone found another way?

推荐答案

我正在跑步,只是写了一个小模块来抽象。以下是它的使用方式。它是使用express 3编写和测试,所以应该工作正常连接2.4.x.请允许我知道。

I was running into the same and just wrote a tiny module to abstract it. Here's how its usage looks like. It was written and tested using express 3 so should work fine with connect 2.4.x. Please let me know otherwise.

var SessionSockets = require('session.socket.io')
  , sessionSockets = new SessionSockets(io, sessionStore, cookieParser);

sessionSockets.on('connection', function (err, socket, session) {
  //your regular socket.io code goes here
});

有关其工作原理的详细信息,请参阅

For more details on how it works see https://github.com/functioncallback/session.socket.io

这篇关于socket.io解析连接(> = 2.4.1)签名会话cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 14:29