Bu çok geç bir yanıttır, ancak umarım sizin kullanımınıza olacaktır. Bu sorunu çözmek için dört saatimi harcadım.
Çalışacağınız ilk konu, koa-session
'un gerçek oturum depolarını kullanmamasıdır. Çerezdeki tüm bilgileri katıştırır ve ardından istemciye gönderir. Bu uygun olsa da, Socket.IO
'un koa-session
'a erişimi olmadığı için, Socket.IO
'u dahil etmeye çalışırken size karşı çalışır.
Oturumlarınızı takip etmek için koa-generic-session
'a geçmeniz ve bir oturum deposu kullanmanız gerekir. Bu benim düşünceme göre, daha iyi bir hamle olsun. Şu anda oturumlarım için koa-redis
kullanıyorum.
Oturumlarınıza Socket.IO
numaralı telefondan erişmek için global bir mağaza kurmanız gerekir. İşte benim global mağazamın neye benzediği.
// 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);
}
Bundan sonra, ilk kurulum kolaydır.
// 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 ...
Artık küresel bir oturum depolamasını sahip olduğunu, daha sonra Socket.IO
yılında erişebilirsiniz. Lütfen cookie
ve co
modüllerini kurmanız gerekeceğini unutmayın.
// 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 kodunu değiştirdim. Umarım bu yardımcı olur.
Firefox (v. 36) websocket istekleri ile çerez göndermeyen gibi görünüyor, bu nedenle burada çalışmaz. Web sayfasının, soketlerin her istekte sunucuya geri gönderilebileceği bir belirteç aldığı ve bu yollarla onaylanabileceği bir çözüm arıyorum. –
Çok teşekkürler, benim için çalıştı! – amd