【已解决】关于 socket.io 的(session的认证),获取不到
发布于 12 年前 作者 zcl521ss 11046 次浏览 最后一次编辑是 8 年前
 io.set('authorization', function (handshakeData, callback)
    {
        if (!handshakeData.headers.cookie)
        {
            return callback('no found cookie', false);
        }
        handshakeData.cookie =parseCookie(handshakeData.headers.cookie);
        console.log("handshakeData:" + handshakeData.headers.cookie + "&&&&&&&" + handshakeData.cookie);
        var connect_sid = handshakeData.cookie['connect.sid'];
        console.log("connect_sid:" + connect_sid);
        if (connect_sid)
        {
            storeMemory.get(connect_sid, function (error, session)
            {
                if (error)
                {
                    callback(error.message, false);
                    console.log("session:" + session);
                }
                else
                {
                    handshakeData.session = session;
          !!这里:  console.log("handshakeData.session:" + handshakeData.session);
                    callback(null, true);
                }
            });
        }
        else
        {
            callback('nosession');
        }
    });

日志是这样的 handshakeData:connect.sid=I9L8i7ofxMs%2BzI8%2FBGsSpnpu.zWvUkOt4%2BNlroy0I%2FpLBC3HRbnT6GjzPibo%2FDi%2BPvQk&&&&&&&[object Object]

connect_sid:I9L8i7ofxMs+zI8/BGsSpnpu.zWvUkOt4+Nlroy0I/pLBC3HRbnT6GjzPibo/Di+PvQk

这个就是上面的handshakeData.session:undefined

debug: authorized

info: handshake authorized SWmx1XIsmVBW5_9CnBE_

后面用

var session = socket.handshake.session;
var name = session.user;

错误出现 Cannot read property ‘user’ of undefined

2 回复

storeMemory这个方法是怎么写的?

var storeMemory = new MemoryStore({ reapInterval: 60000 * 10 });

不过最后好了

主要是

,connect = require(‘connect’) ,cookie = require(‘cookie’) ,MemoryStore = connect.middleware.session.MemoryStore

connect的引用我开始是用的express里的,后来单独下载了connect, 然后下面用

handshakeData.cookie = connect.utils.parseSignedCookies(cookie.parse(decodeURIComponent(handshakeData.headers.cookie)),"zcl");

希望有同样错误的同学可以借鉴一下

回到顶部