以下で多くのコメントが指摘されているように、Socket.IOAPIは1.0
リリースで変更されました。これで、認証はミドルウェア機能を介して実行されるはずです。「認証の違い」@http ://socket.io/docs/migrating-from-0-9/#authentication-differencesを参照してください。古いドキュメントがなくなったように見えるので、1.0未満で立ち往生している人のための私の元の答えを含めます。
1.0以降:
クライアント側:
//The query member of the options object is passed to the server on connection and parsed as a CGI style Querystring.
var socket = io("http://127.0.0.1:3000/", { query: "foo=bar" });
サーバ側:
io.use(function(socket, next){
console.log("Query: ", socket.handshake.query);
// return the result of next() to accept the connection.
if (socket.handshake.query.foo == "bar") {
return next();
}
// call next() with an Error if you need to reject the connection.
next(new Error('Authentication error'));
});
1.0より前
2番目の引数にquery:paramを渡して、クライアント側のconnect()に渡すことができます。これは、サーバーの承認メソッドで使用できます。
私はちょうどそれをテストしています。私が持っているクライアントで:
var c = io.connect('http://127.0.0.1:3000/', { query: "foo=bar" });
サーバー上:
io.set('authorization', function (handshakeData, cb) {
console.log('Auth: ', handshakeData.query);
cb(null, true);
});
サーバー上の出力は次のようになりました。
:!node node_app/main.js
info - socket.io started
Auth: { foo: 'bar', t: '1355859917678' }
アップデート
3.x以降
クライアント側のconnect()の2番目の引数としてauth paramを使用して、認証ペイロードを渡すことができます。
クライアント側:
io.connect("http://127.0.0.1:3000/", {
auth: {
token: "AuthToken",
},
}),
サーバー側では、を使用してアクセスできますsocket.handshake.auth.token
サーバ側:
io.use(function(socket, next){
console.log(socket.handshake.auth.token)
next()
});