因此,我有一个运行node js和socket的应用程序.io作为后端,普通javascript作为前端.我的应用程序有一个登录系统,目前只是让客户端在连接后立即发送其登录数据.

现在我想,让登录数据与握手数据一起发送会更好,这样我可以直接让用户在连接时登录(而不是在建立连接后),当登录数据无效时,分别拒绝授权.

我想最好是把我的附加数据放在握手数据的标题部分,所以有什么办法吗?(如果可能的话,无需修改socket.io,但如果这是我唯一可以接受的方式)

推荐答案

正如许多 comments 在插座下面指出的那样.IO API在1.0版本中发生了变化.现在应该通过中间件功能进行身份验证,请参阅@http://socket.io/docs/migrating-from-0-9/#authentication-differences的"身份验证差异".我会把我的原始答案告诉所有被困的人<;1.0,因为旧文档似乎已经不见了.

1.0 and later:

客户端:

//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'));
});

Pre 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 and later

可以使用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()
});

Node.js相关问答推荐

已知NPM无法在node.js V12上运行的问题

如何在Mongoose for MongoDB中编写此查询

try 插入重复的邮箱时,mongoDB DuplicateKey 错误未定义

Express Web 服务器部署到 prod 但 GET 返回超时错误

如果我在父文件夹中运行,子进程生成不起作用

处理 UTC 日期和future

如何在没有 Typescript 的情况下以交互方式使用 Create-React-App?

如何在 NestJS 中使用外部生成的 swagger.json?

BrowserRouter工作时为什么HashRouter不工作?

我怎样才能让`git`失败而不是要求提供凭据

后端位于 Docker 容器中时的 SvelteKit SSR fetch()

配额超出了每分钟的 Sheets API 写入请求数. node .js

try 运行迁移时的 Typeorm:缺少必需的参数:dataSource

使用 node.js 执行一个 exe 文件

构建 vue cli 后如何运行生产站点

如何将`yarn.lock`与`package.json`同步?

错误:大多数中间件(如 bodyParser)不再与 Express Bundle

在 Jade 包含中使用变量

- configuration.output.path:提供的值public不是绝对路径!使用 Webpack

mongoose 填充与对象嵌套