获取用户id socket.io、护照、koa

Get user id socket.io, passport, koa

本文关键字:护照 koa io socket 用户 id 获取      更新时间:2023-09-26

我使用Koa、Passport.js和Koa会话对用户进行身份验证。所以它基本上看起来像:

// session
var session = require('koa-session');
app.keys = [config.secret];
app.use(session());

// auth
require(__dirname+'/lib/auth'); // de/serializeUser, strategies etc..
var passport = require('koa-passport');
app.use(passport.initialize());
app.use(passport.session());

这很有效。在请求时,我确实有带用户id的req.user。但当使用套接字时,我可以做:

io.on('connection', function(socket) {
  console.log(socket.request.headers.cookie),
});

当然,这只是加密的会话ID,我如何反序列化用户并获得user.ID,就像我在获取或发布请求时获得req.user一样?

提前谢谢。

这是一个非常晚的响应,但我希望它对您有用。

您将遇到的第一个问题是koa-session不使用真正的会话存储。它将所有信息嵌入cookie本身,然后将其解析到客户端和从客户端解析出来。虽然这可能很方便,但在尝试合并Socket.IO时会对您不利,因为Socket.IO无法访问koa-session

您需要迁移到koa-generic-session并使用会话存储来跟踪您的会话。无论如何,在我看来,这是一个更好的举措。我当前正在将koa-redis用于会话存储。

为了能够访问Socket.IO中的会话,您需要设置一个全局存储。这是我的全球商店的样子。

// store.js
var RedisStore = require('koa-redis'),
    store = undefined; // global
module.exports = function(app, settings) {
    // Where (app) is Koa and (settings) is arbitrary information
    return (function(app, settings) {
        store = store || new RedisStore();
        return store;
    })(app, settings);
}

之后,初始设置就很容易了。

// app.js
... arbitrary code here ...
var session = require('koa-generic-session');
app.keys = [config.secret];
app.use(session({
    store: require('./store')(app, settings)
}));
... arbitrary code here ...
    

现在您有了全局会话存储,然后可以在Socket.IO中访问它。请记住,您需要安装cookieco模块。

// io.js
var cookie = require('cookie'),
    co = require('co'),
    store = require('./store')(null, settings); // We don't require the Koa app
io.use(function(socket, next){
    // Now you will need to set up the authorization middleware. In order to
    // authenticate, you will need the SID from the cookie generated by
    // koa-generic-session. The property name is by default 'koa.sid'.
    var sid = cookie.parse(socket.handshake.headers.cookie)['koa.sid'];
    // We need co to handle generators for us or everything will blow up
    // when you try to access data stores designed for Koa.
    co(function*(){
        // 'koa:sess:' is the default prefix for generic sessions.
        var session = yield store.get('koa:sess:' + sid);
        
        // At this point you can do any validation you'd like. If all is well,
        // authorize the connection. Feel free to add any additional properties
        // to the handshake from the session if you please.
        if (session) next(null, true) // authenticated
        else throw new Error('Authentication error.');
    });
});
io.on('connection', function(socket){
    // Access handshake here.
});

我已经调整了Socket.IO v1的代码。我希望这能有所帮助。

我使用正则表达式获取userId,然后在数据库中找到。这不是最干净的方法,但效果很好。我只是使用koa会话存储作为我的passport js会话。

  var cookies = socket.request.headers.cookie;
  var regEx = /passport"':'{"user"':"(.+?)"'}/g
  var userIdMatches = regEx.exec(cookies);