简体   繁体   English

护照没有出现在 session socket.io

[英]Passport not showing up in session socket.io

The Problem问题
I am trying to authenticate users based on my express session similar to this post.我正在尝试根据类似于这篇文章的我的快递 session 对用户进行身份验证。 In http request this is what req.session returns I also connected my mongo store to hold sessions but it also behaves like socket session returning only cookie without session information. In http request this is what req.session returns I also connected my mongo store to hold sessions but it also behaves like socket session returning only cookie without session information.

//user not authenticated    
Session {
 cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true },
 passport: {}
        }
//user authenticated
Session {
  cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true },
  passport: {
    user: {
      _json: [Object],
      id: '76561198298457222',
    }

But when i try to socket.request.session with socket io using the post refrenced passport object is not returned.但是,当我尝试使用后引用护照 object 与套接字 io 连接 socket.request.session 时,不会返回。 But i am pretty sure that the middleware works beacuse otherwise there is no session at all.但我很确定中间件可以正常工作,否则根本就没有 session。

// user not authenticated
Session {
  cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }
}// user should be authenticated
Session {
  cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }
}

Setup:设置:

   var sessionMiddleware = session({
        secret: '<secret>',
        name: 'profile_session',
        resave: true,
        saveUninitialized: true,
        store: new MongoStore({ mongooseConnection: mongoose.connection })
    })
    app.use(sessionMiddleware);
io.use(function (socket, next) {
    // Wrap the express middleware
    sessionMiddleware(socket.request, {}, next);
})
io.on('connection', (socket) => {
    console.log('a user connected id:', socket.id);
    console.log(socket.request.session)

});

It seems like problem is saveUninitialized is set to true and it saves the session even when there is no user logged in. Also u can use middleware in the io and get the user information.似乎问题是saveUninitialized设置为 true,即使没有用户登录,它也会保存 session。您也可以使用io中的中间件并获取用户信息。

var sessionMiddleware = session({
    secret: '<secret>',
    name: 'profile_session',
    resave: true,
    saveUninitialized: false,
    store: new MongoStore({ mongooseConnection: mongoose.connection })
})

const wrap = (middleware) => (socket, next) => middleware(socket.request, {}, next);
io.use(wrap(sessionMiddleware));
io.use(wrap(passport.initialize()));
io.use(wrap(passport.session()));

io.on("connection", (socket) => {
    const session = socket.request.session;
    const user = socket.request.user
    console.log(session)
    console.log(user)
})

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

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