4

寻找如何设置 HTTPS 与greenlock-express结合安全 websocket 服务器的示例。

4

1 回答 1

3

这就是我最终设置它的方式。关键是使用 greenlock-express 生成的 tslOptions 手动设置一个 HTTPS 服务器,然后以正常方式附加一个 Websocket 服务器。使用这种方法,必须手动完成从 HTTP 到 HTTPS 的重定向。

我最初无法让事情正常工作,因为我没有在我的服务器上打开端口 443。确保你这样做,否则 HTTPS 将无法工作!

const express = require('express');
const http = require('http');
const https = require('https');
const WebSocket = require('ws');

//EXPRESS TO BUNDLE APP
let my_app = express();
let dir = __dirname + '/../app';
io_app.use(express.static(dir));
//Just serving static files from a sibling directory called /app

//// SETUP HTTP GREENLOCK

let greenlock = require('greenlock-express').create({

  // Let's Encrypt v2 is ACME draft 11
  version: 'draft-11'

    ,
  server: 'https://acme-v02.api.letsencrypt.org/directory'
    // Note: If at first you don't succeed, switch to staging to debug
    // https://acme-staging-v02.api.letsencrypt.org/directory

    // You MUST change this to a valid email address
    ,
  email: 'test@example.com'

    // You MUST NOT build clients that accept the ToS without asking the user
    ,
  agreeTos: true

    // You MUST change these to valid domains
    // NOTE: all domains will validated and listed on the certificate
    ,
  approveDomains: ['example.com', 'www.example.com']

    // You MUST have access to write to directory where certs are saved
    // ex: /home/foouser/acme/etc
    ,
  configDir: require('path').join(require('os').homedir(), 'acme', 'etc')

    // Join the community to get notified of important updates and help me make greenlock better
    ,
  communityMember: true

    // Contribute telemetry data to the project
    ,
  telemetry: true

    ,
  debug: true

});

//// REDIRECT HTTP TO HTTPS

let redirectHttps = require('redirect-https')();
let acmeChallengeHandler = greenlock.middleware(redirectHttps);
http.createServer(acmeChallengeHandler).listen(80, function() {
  console.log("Listening for ACME http-01 challenges on", this.address());
});

//// HTTPS SERVER + WEBSOCKETS

let server = https.createServer(greenlock.tlsOptions, my_app);

let ws = new WebSocket.Server({
  server
});

ws.on('connection', function(ws, req) {
  //websocket on connection... 
});

server.listen(443);

于 2018-06-23T23:11:20.290 回答