How it works...

Running the preceding code is enough to get encrypted connections to your server. (Of course, if you use self-signed certificates, the end user will get warnings about the lack of actual security, but you would get valid certificates, wouldn't you?) We can see the result of this in the following screenshot—and keep in mind that with real certificates, the user would get no alerts about your unsafe site!

 Installing certificates and using HTTPS instead of HTTP generates a secure server.
Of course, since we made up the certificate by ourselves, Google Chrome doesn't really like the site!

We can also force HTTP users to work with HTTPS by running a second server, this time with HTTP, and redirecting all traffic to our first server, which is secure:

// Source file: src/http_server.js

/* @flow */
"use strict";

const express = require("express");
const app = express();
const http = require("http");

http.createServer(app).listen(8080);

app.use((req, res, next) => {
if (req.secure) {
next();
} else {
res.redirect(
`https://${req.headers.host.replace(/8080/, "8443")}${req.url}`
);
}
});

A Node server can only listen to a single port, so you'd run this server as a separate instance. Now, if you try to use HTTP to access your server, you'll be redirected automatically, a good practice!

Adding secure connections is simple; let's keep on working on more security aspects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset