使用 Socket.IO 进行授权和握手
发布于 3 年前 作者 gocpplua 1578 次浏览 来自 分享

我们的授权可以通过使用中间件,如下完成:

const io = require('socket.io-client')
const host = "https://127.0.0.1"
const port =  3001;
console.log(io.connect)
const options = {
  secure:true,
  rejectUnauthorized : false,
  transportOptions: {
    polling: {
      extraHeaders: {
        authorization': 'gocpplua',
      },
    },
  }
  };
const uri = `${host}:${port}?token=abc`
const socket = io.connect(uri, options);

上面其实是使用了两种方式:

  1. 通过添加token=abc
  2. 通过携带额外的请求头 extraHeaders

服务器添加中间件:

const option = {
        "key": "X", 'utf8'),
        "cert": "X", 'utf8'),
        "transports": ["websocket", "xhr-polling", "htmlfile", "jsonp-polling"],
        'pingInterval': 5000,
        'pingTimeout': 30000
    };
var httpsServer = require('https').createServer(option);
var ssio = require('socket.io')(httpsServer);
ssio.set('authorization', function (handshake, callback) {
        if (handshake.headers.authorization == 'gocpplua') { // 这里只用了authorization校验,我们还可以使用handshake._query.token校验
            return callback(null, true);
        }
        return callback(new Error('authentication '));
    });

连接的时候,服务器调试得到的参数如下:

  1. handshake._query.token -> abc
  2. handshake.headers.authorization -> chenqi

我们可以通过校验上面两者,来判断要不要继续进行链接。

参考文章:

回到顶部