简体   繁体   中英

NodeJS add SSL to HTTPserver

I'm trying to add SSL to HTTPserver of an example WebRTC Video Chat application. I have allready tried to add SSL to my Lighttpd and just Proxy, but the Socket.IO connection don't work besouse of mixed https/non https content. I think i need a standalone node https server application for this. I'm new in Node and need some help...

This is my App:

index.ts

import { Server } from "./server";

const server = new Server();

server.listen(port => {
  console.log(`Server is listening on http://localhost:${port}`);
});

server.ts

import express, { Application } from "express";
import socketIO, { Server as SocketIOServer } from "socket.io";
import { createServer, Server as HTTPServer } from "http";
import path from "path";

export class Server {
  private httpServer: HTTPServer;
  private app: Application;
  private io: SocketIOServer;

  private activeSockets: string[] = [];

  private readonly DEFAULT_PORT = +process.env.PORT || 3000;

  constructor() {
    this.initialize();
  }

  private initialize(): void {
    this.app = express();
    this.httpServer = createServer(this.app);
    this.io = socketIO(this.httpServer);

    this.configureApp();
    this.configureRoutes();
    this.handleSocketConnection();
  }

  ...

  public listen(callback: (port: number) => void): void {
    this.httpServer.listen(this.DEFAULT_PORT, () => {
      callback(this.DEFAULT_PORT);
    });
  }
}

Use https library instead of http :

const https = require('https');
const fs = require('fs');
const privateKey = fs.readFileSync('./localhost.key', 'utf8');
const certificate = fs.readFileSync('./localhost.crt', 'utf8');

const credentials = {
  key: privateKey,
  cert: certificate,
};

const httpsServer = https.createServer(credentials, this.app);

The self-signed cert can be generated like so:

openssl req -x509 -out localhost.crt -keyout localhost.key \
  -newkey rsa:2048 -nodes -sha256 \
  -subj '/CN=localhost' -extensions EXT -config <( \
   printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")

See https://letsencrypt.org/docs/certificates-for-localhost/#making-and-trusting-your-own-certificates for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM