获取用户名socket.io,passport,koa

Coh*_*ars 5 javascript session node.js socket.io koa

我正在使用Koa,Passport.js和koa-session对用户进行身份验证.所以它基本上看起来像:

// 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());
Run Code Online (Sandbox Code Playgroud)

这很好用.根据请求,我确实拥有req.user用户ID.但是当使用套接字时,我可以这样做:

io.on('connection', function(socket) {
  console.log(socket.request.headers.cookie),
});
Run Code Online (Sandbox Code Playgroud)

但是当然它只是加密的会话ID,我怎样才能反序列化用户并获得user.id就像我req.user在获取或发送请求时一样?

先感谢您.

dim*_*uel 10

这是一个非常晚的回复,但我希望它对你有用.我花了大约四个小时试图解决这个问题.

您将遇到的第一个问题是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);
}
Run Code Online (Sandbox Code Playgroud)

之后,初始设置很容易.

// 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 ...
Run Code Online (Sandbox Code Playgroud)

现在您已拥有全局会话存储,然后可以访问它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.
});
Run Code Online (Sandbox Code Playgroud)

我调整了Socket.IOv1 的代码.我希望这有帮助.