正如许多 cmets 在其1.0 版本中更改的 Socket.IO API 下面所指出的那样。现在应该通过中间件功能完成身份验证,请参阅“身份验证差异”@http://socket.io/docs/migrating-from-0-9/#authentication-differences。由于旧文档似乎已经消失,我将为停留在
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
您可以将第二个参数中的 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 及更高版本
您可以使用 auth 参数作为客户端中 connect() 的第二个参数传递身份验证负载。
客户端:
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()
});