[英]Get user id socket.io, passport, 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());
這很好用。 在請求我有req.user
,用戶ID。 但是當使用套接字時,我可以這樣做:
io.on('connection', function(socket) {
console.log(socket.request.headers.cookie),
});
但是當然它只是加密的會話ID,我怎樣才能反序列化用戶並獲取user.id,就像我在獲取或發送請求時得到req.user
?
先感謝您。
這是一個非常晚的回復,但我希望它對你有用。 我花了大約四個小時試圖解決這個問題。
您將遇到的第一個問題是koa-session
不使用真正的會話存儲。 它將所有信息嵌入cookie本身,然后將其解析到客戶端和從客戶端解析。 雖然這很方便,但在嘗試合並Socket.IO
時會對您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的代碼。 我希望這有幫助。
我使用正則表達式來獲取userId然后在我的數據庫中找到。 不是最干凈的方法,但它運作良好。 我只是使用koa-session-store作為我與護照js的會話。
var cookies = socket.request.headers.cookie;
var regEx = /passport"\:\{"user"\:"(.+?)"\}/g
var userIdMatches = regEx.exec(cookies);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.