我正在尝试使用Passport保护我的Socket.io连接,但是我不确定如何做到这一点。我的目标是防止任何客户端在未登录的情况下访问Socket.io API。
我有一个用于Passport的登录路线(POST):
app.post('/api/v1/login', passport.authenticate('local-login'), function(req, res) {
res.json({
login: true,
id: req.user._id,
username: req.user.local.username
});
});
如果登录成功,这会将布尔值,用户ID和用户名发送回客户端。
然后我有Socket.io代码:
io.use(function(socket, next) {
sessionMiddleware(socket.request, {}, next);
}).on('connection', function(socket) {
logger.info('Client has connected. {id=' + socket.id + '; address=' + socket.request.connection.remoteAddress + '; session=' + JSON.stringify(socket.request.session) + '}');
socket.on('disconnect', function() {
logger.info('Client has disconnected. {id=' + socket.id + '; address=' + socket.request.connection.remoteAddress + '}');
});
socket.on('post_public_message', function(message) {
logger.info('Client posts public message. {id=' + socket.id + '; message=' + message + '}');
});
});
这是我的Passport配置:
passport.use('local-login', new LocalStrategy(function(username, password, done) {
logger.info('Trying to authorize user. {username=' + username + '}');
User.findOne({
'local.username': username
}, function(err, user) {
if (err) {
logger.error('Failed to authorize user. {username=' + username + +'; err=' + err + '}');
return done(err);
}
if (!user) {
logger.info('User could not be found. {username=' + username + '}');
return done(null, false, {
message: 'Invalid username.'
});
}
if (!user.validPassword(password)) {
logger.info('Invalid password for user. {username=' + username + '}');
return done(null, false, {
message: 'Invalid password.'
});
}
logger.info('Successfully authorized user. {username=' + username + '}');
return done(null, user);
});
}));