因此,我有一个运行node js和socket的应用程序.io作为后端,普通javascript作为前端.我的应用程序有一个登录系统,目前只是让客户端在连接后立即发送其登录数据.
现在我想,让登录数据与握手数据一起发送会更好,这样我可以直接让用户在连接时登录(而不是在建立连接后),当登录数据无效时,分别拒绝授权.
我想最好是把我的附加数据放在握手数据的标题部分,所以有什么办法吗?(如果可能的话,无需修改socket.io,但如果这是我唯一可以接受的方式)
因此,我有一个运行node js和socket的应用程序.io作为后端,普通javascript作为前端.我的应用程序有一个登录系统,目前只是让客户端在连接后立即发送其登录数据.
现在我想,让登录数据与握手数据一起发送会更好,这样我可以直接让用户在连接时登录(而不是在建立连接后),当登录数据无效时,分别拒绝授权.
我想最好是把我的附加数据放在握手数据的标题部分,所以有什么办法吗?(如果可能的话,无需修改socket.io,但如果这是我唯一可以接受的方式)
正如许多 comments 在插座下面指出的那样.IO API在1.0
版本中发生了变化.现在应该通过中间件功能进行身份验证,请参阅@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'));
});
您可以将第二个参数中的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' }
可以使用auth param作为客户端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()
});