我知道這有點舊了,但對於未來的讀者,除了解析cookie並從存儲中檢索會話(例如,passport.socketio)之外,您還可以考慮基於標記的方法。
在這個例子中,我使用了非常標準的JSON Web Tokens。你必須給到客戶端頁面的標記,在這個例子中想象返回JWT認證端點:
var socketioJwt = require('socketio-jwt');
var sio = socketIo.listen(server);
sio.set('authorization', socketioJwt.authorize({
secret: jwtSecret,
handshake: true
}));
sio.sockets
.on('connection', function (socket) {
console.log(socket.handshake.decoded_token.email, 'has joined');
//socket.on('event');
});
的:
var jwt = require('jsonwebtoken');
// other requires
app.post('/login', function (req, res) {
// TODO: validate the actual user user
var profile = {
first_name: 'John',
last_name: 'Doe',
email: '[email protected]',
id: 123
};
// we are sending the profile in the token
var token = jwt.sign(profile, jwtSecret, { expiresInMinutes: 60*5 });
res.json({token: token});
});
現在,您socket.io服務器可以配置如下socket.io,智威湯遜中間件預計在查詢字符串令牌,因此從客戶端你只需要連接它連接時:
var socket = io.connect('', {
query: 'token=' + token
});
我寫了這個甲基更詳細的解釋od和cookies here。
您是否將Socket.IO作爲獨立使用?驗證器不會創建cookie,只是將它們傳遞給Socket.IO。 – hexacyanide
@hexacyanide目前我正在使用express和socket.io。 Express僅創建auth cookie。我不使用它的路由,中間件.... express和socket.io之間的Session與connect-redis共享。我認爲這是一種太大的依賴性,只能使用express來簽署cookie。所以我正在尋找一個不依賴快遞(連接)的解決方案。我可以實現我自己的未經測試和不安全的認證程序,但像Golo Roden認爲這不是可取的。 – bekite
換句話說,你想要一個在基本HTTP服務器上運行的實現?因爲如果你不想完全使用HTTP服務器,那麼你想使用cookie嗎? – hexacyanide