您可以使用Passport.socketio來驗證您的套接字連接。它表現得非常好。下面是一個示例應用程序:
var express = require('express');
var passport = require('passport');
var passportSocketIo = require("passport.socketio");
var cookieParser = require('cookie-parser');
var session = require('express-session');
var app = express();
var RedisStore = require('connect-redis')(session);
var sessionStore = new RedisStore({
host: 'localhost',
port: 6379,
db: 2,
});
app.use(session({
store: sessionStore,
secret: 'YOUR_SECRET_HERE'
}));
app.use(passport.initialize());
app.use(passport.session());
var io = require('socket.io').listen(http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
}));
io.use(passportSocketIo.authorize({
cookieParser: cookieParser,
secret: 'YOUR_SECRET_HERE',
store: sessionStore,
}));
對於您的情況,您必須將角色添加到您的護照用戶。該用戶信息然後可以在訪問socket.request.user
io.sockets.on('connection', function(socket) {
var user = socket.request.user;
if (user.role == true){
//do something
}
});
請注意,你必須使用一個sessionStore,本地存儲不與護照工作。請參閱上面的Git頁面以瞭解不同的可能性。