大変遅くなりましたが、お役に立てれば幸いです。この問題の解決に約 4 時間費やしました。
最初に遭遇する問題は、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
. cookie
およびco
モジュールをインストールする必要があることに注意してください。
// 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のコードを調整しました。これが役立つことを願っています。