Setup Server-Server SSL communication using socket.io in node.js

ぐ巨炮叔叔 提交于 2019-11-27 20:19:28
stevo

I've had to do things a little differently on the client to get this to work, by manually telling socket.io to use that Agent as well (and the secure: true is implied by https:). Here it is:

// Client
var io = require('socket.io-client');
var https = require('https');
https.globalAgent.options.rejectUnauthorized = false;
var socket = io.connect('https://localhost:3210/', { agent: https.globalAgent });
socket.on('connect', function(){ console.log('connected'); });

This is using socket.io v1.0.2.

Alternatively, I've had success with the following as well, as pointed to here: Socket.io + SSL + self-signed CA certificate gives error when connecting

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
var io = require('socket.io-client');
var socket = io.connect('https://localhost:3210/');
socket.on('connect', function(){ console.log('connected'); });

After some more searching, adding this in the client makes it work:

require('https').globalAgent.options.rejectUnauthorized = false;

/**
 * Client
 */


var io = require('socket.io-client');
//var socket = io.connect('http://localhost', {port: 8088});

require('https').globalAgent.options.rejectUnauthorized = false; 

var socket = io.connect('https://localhost', {secure: true, port: 8088});
  socket.on('connect', function(){
    socket.on('event', function(data){});
    socket.on('disconnect', function(){});
  });

The previous answers didn't do it for me. require('https').globalAgent is always undefined.

Did some seaching and found the rejectUnauthorized parameter in the docs (https://nodejs.org/api/tls.html). Not sure if it's related to SocketIO, but it somehow seems to work with self-signed certificates:

var socket = io.connect('//yourhost:8000', {secure: true, rejectUnauthorized: false})

secure: true might be optional, but I like to enforce it anyhow.

While all the above solutions focus on rejectUnauthorized=false, I'd like to suggest an alternative.

const https = require('https');
const rootCas = require('ssl-root-cas').create();
rootCas.addFile('cert/ca.crt');
https.globalAgent.options.ca = rootCas; // optional

const io = require("socket.io-client");
var socket = io.connect("https://...", { agent: https.globalAgent });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!