Using HTTPS over HTTP

In a tweet, the first and most important thing that you should do is always use HTTPS over HTTP. We know that this is sometimes difficult during the development process, because there is no valid certificate, but this should not prevent you from doing so. You can run HTTPS locally with a self-signed certificate.

For local testing, we will use OpenSSL to generate a key and the certificates for HTTPS configuration. 

The OpenSSL documentation is available at https://www.openssl.org/docs/.

Once you have OpenSSL configured, go to the root folder of the order-api project and create a new certificate there. The command to create a certificate on macOS is as follows:

$ openssl req -newkey rsa:2048 -nodes -keyout keytemp.pem -x509 -days 365 -out cert.pem
$ openssl rsa -in keytemp.pem -out key.pem

This command will generate a new key and cert file for you. Right after creating those files, make sure to add them as part of the .gitignore file if you are using Git.

Right after creating these files, move them to a new folder called config, under the root level of the order-api project, and change the src/server.ts file to allow HTTPS connections:

import * as fs from 'fs'
import * as https from 'https'
import app from './app'

const PORT = process.env.PORT

const httpsOptions = {
key: fs.readFileSync('./config/key.pem'),
cert: fs.readFileSync('./config/cert.pem'),
}
https.createServer(httpsOptions, app).listen(PORT)

Now, if you start the application, the URIs should be available only on the HTTPS level:

Requests over HTTPS

If we try to call HTTP, we should not be able to get the connection with the server, as follows:

Request denied through HTTP
..................Content has been hidden....................

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