Using https on express 4.0 [duplicate] - node.js

Given an SSL key and certificate, how does one create an HTTPS service?

The Express API doc spells this out pretty clearly.
Additionally this answer gives the steps to create a self-signed certificate.
I have added some comments and a snippet from the Node.js HTTPS documentation:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.cert')
};
// Create a service (the app object is just a callback).
var app = express();
// Create an HTTP service.
http.createServer(app).listen(80);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);

For Node 0.3.4 and above all the way up to the current LTS (v16 at the time of this edit), https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener has all the example code you need:
const https = require(`https`);
const fs = require(`fs`);
const options = {
key: fs.readFileSync(`test/fixtures/keys/agent2-key.pem`),
cert: fs.readFileSync(`test/fixtures/keys/agent2-cert.pem`)
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end(`hello world\n`);
}).listen(8000);
Note that if want to use Let's Encrypt's certificates using the certbot tool, the private key is called privkey.pem and the certificate is called fullchain.pem:
const certDir = `/etc/letsencrypt/live`;
const domain = `YourDomainName`;
const options = {
key: fs.readFileSync(`${certDir}/${domain}/privkey.pem`),
cert: fs.readFileSync(`${certDir}/${domain}/fullchain.pem`)
};

Found this question while googling "node https" but the example in the accepted answer is very old - taken from the docs of the current (v0.10) version of node, it should look like this:
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);

The above answers are good but with Express and node this will work fine.
Since express create the app for you, I'll skip that here.
var express = require('express')
, fs = require('fs')
, routes = require('./routes');
var privateKey = fs.readFileSync('cert/key.pem').toString();
var certificate = fs.readFileSync('cert/certificate.pem').toString();
// To enable HTTPS
var app = module.exports = express.createServer({key: privateKey, cert: certificate});

The minimal setup for an HTTPS server in Node.js would be something like this :
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-crt.pem')
};
var app = function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}
https.createServer(httpsOptions, app).listen(4433);
If you also want to support http requests, you need to make just this small modification :
var http = require('http');
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-crt.pem')
};
var app = function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}
http.createServer(app).listen(8888);
https.createServer(httpsOptions, app).listen(4433);

Update
Use Let's Encrypt via Greenlock.js
Original Post
I noticed that none of these answers show that adding a Intermediate Root CA to the chain, here are some zero-config examples to play with to see that:
https://github.com/solderjs/nodejs-ssl-example
http://coolaj86.com/articles/how-to-create-a-csr-for-https-tls-ssl-rsa-pems/
https://github.com/solderjs/nodejs-self-signed-certificate-example
Snippet:
var options = {
// this is the private key only
key: fs.readFileSync(path.join('certs', 'my-server.key.pem'))
// this must be the fullchain (cert + intermediates)
, cert: fs.readFileSync(path.join('certs', 'my-server.crt.pem'))
// this stuff is generally only for peer certificates
//, ca: [ fs.readFileSync(path.join('certs', 'my-root-ca.crt.pem'))]
//, requestCert: false
};
var server = https.createServer(options);
var app = require('./my-express-or-connect-app').create(server);
server.on('request', app);
server.listen(443, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
var insecureServer = http.createServer();
server.listen(80, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
This is one of those things that's often easier if you don't try to do it directly through connect or express, but let the native https module handle it and then use that to serve you connect / express app.
Also, if you use server.on('request', app) instead of passing the app when creating the server, it gives you the opportunity to pass the server instance to some initializer function that creates the connect / express app (if you want to do websockets over ssl on the same server, for example).

To enable your app to listen for both http and https on ports 80 and 443 respectively, do the following
Create an express app:
var express = require('express');
var app = express();
The app returned by express() is a JavaScript function. It can be be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.
You can do so as follows:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
For complete detail see the doc

You can use also archive this with the Fastify framework:
const { readFileSync } = require('fs')
const Fastify = require('fastify')
const fastify = Fastify({
https: {
key: readFileSync('./test/asset/server.key'),
cert: readFileSync('./test/asset/server.cert')
},
logger: { level: 'debug' }
})
fastify.listen(8080)
(and run openssl req -nodes -new -x509 -keyout server.key -out server.cert to create the files if you need to write tests)

If you need it only locally for local development, I've created utility exactly for this task - https://github.com/pie6k/easy-https
import { createHttpsDevServer } from 'easy-https';
async function start() {
const server = await createHttpsDevServer(
async (req, res) => {
res.statusCode = 200;
res.write('ok');
res.end();
},
{
domain: 'my-app.dev',
port: 3000,
subdomains: ['test'], // will add support for test.my-app.dev
openBrowser: true,
},
);
}
start();
It:
Will automatically add proper domain entries to /etc/hosts
Will ask you for admin password only if needed on first run / domain change
Will prepare https certificates for given domains
Will trust those certificates on your local machine
Will open the browser on start pointing to your local server https url

Download rar file for openssl set up from here: https://indy.fulgan.com/SSL/openssl-0.9.8r-i386-win32-rev2.zip
Just copy your folder in c drive.
Create openssl.cnf file and download their content from : http://web.mit.edu/crypto/openssl.cnf
openssl.cnf can be put any where but path shoud be correct when we give in command prompt.
Open command propmt and set openssl.cnf path C:\set OPENSSL_CONF=d:/openssl.cnf
5.Run this in cmd : C:\openssl-0.9.8r-i386-win32-rev2>openssl.exe
Then Run OpenSSL> genrsa -des3 -out server.enc.key 1024
Then it will ask for pass phrases : enter 4 to 11 character as your password for certificate
Then run this Openssl>req -new -key server.enc.key -out server.csr
Then it will ask for some details like country code state name etc. fill it freely.
10 . Then Run Openssl > rsa -in server.enc.key -out server.key
Run this OpenSSL> x509 -req -days 365 -in server.csr -signkey server.key -out server.crt then use previous code that are on stack overflow
Thanks

Related

Express Static Directory over HTTPS

I would like to implement Node.js with Express for static content over HTTPS. Scouring the Web reveals tons of examples of Express with HTTPS and tons of examples of Express serving a static directory, but I cannot find an example using all three Express, HTTPS and static.
Moreover, looking at the examples I can find, I cannot piece together how to accomplish this.
Here is what I have found:
Express Static Directory over HTTP
var fs = require('fs')
var app = require("express");
var server = app();
server.use(app.static(staticDir))
server.listen(webPort)
Express over HTTPS (without Static Directory)
const app = require('express')();
const https = require('https');
const server = https.createServer(
{
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
},
app
);
server.listen(APIPort);
When I try combining the two approaches, I get stuck because the static example bypasses createServer, and yet createServer is the crux of getting to HTTPS in the examples.
I'm sure the answer is simple, but I cannot arrive at or locate the solution.
Could you try the below code-snippet and see if it works for you?
const fs = require('fs');
const https = require('https');
const express = require('express');
const app = express();
app.use(express.static(process.env.SERVE_DIRECTORY));
app.get('/', function(req, res) {
return res.end('Serving static files!');
});
const key = fs.readFileSync(__dirname + '/selfsigned.key');
const cert = fs.readFileSync(__dirname + '/selfsigned.crt');
const options = {
key: key,
cert: cert
};
const server = https.createServer(options, app);
server.listen(PORT, () => {
console.log(`Serving on port ${PORT}`);
});
Please make sure to do the suitable changes before running the above code.

HTTPS node js, express can not be changed to green?

I'm trying to change the lock from HTTPS on my localhost from red to green....
var fs = require('fs');
var https = require('https');
var app = require('express')();
var options = {
key: fs.readFileSync('privatekey.pem'),
cert: fs.readFileSync('certificate.pem')
};
app.get('/', function (req, res) {
res.send('Hello World!');
});
https.createServer(options, app).listen(3000, function () {
console.log('Started!');
});
I get the following error in my browser
This page is insecure (broken HTTPS). Certificate Error There are issues with the site's certificate chain (net::ERR_CERT_AUTHORITY_INVALID)
I used OpenSSL to create the certificates. I don't know what more to do with the certificates
You've created self-signed certificates which the OS needs to be told are valid before your browser will allow them. You need to add them to Keychain on a mac or the trusted root certificates. In both cases, double clicking the pem file should bring up the appropriate application at which point you can mark the certificates as trusted.
https://www.digicert.com/csr-creation-ssl-installation-mac-osx-el-capitan.htm
https://blogs.technet.microsoft.com/sbs/2008/05/08/installing-a-self-signed-certificate-as-a-trusted-root-ca-in-windows-vista/

HTTP and HTTPS same time (Express.Io)

I'm successfully listenin port 443 and can access server over https, but I can't access it with http.
var fs = require('fs')
options = {
ca : fs.readFileSync('./ssl/site.com.pem'),
key: fs.readFileSync('./ssl/site.com.key'),
cert: fs.readFileSync('./ssl/site_com.crt')
}
var app = require('express.io')
app.https(options).io()
....
app.listen(443);
I've tried using http and https modules:
app.http().io();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
But this time socket.io is giving 404 in browser. How can I solve this? I need to use Express.Io's socket connection because application is based on it.
You should redirect http to https
var express = require('express'),
app = express(),
httpapp = express();
//........................
var credentials = {key: privateKey, cert: certificate, ca: ca};
var httpsServer = https.createServer(credentials, app);
var httpServer = http.createServer(httpapp);
httpsServer.listen(443);
httpServer.listen(80);
httpapp.route('*').get(function(req,res){
res.redirect('https://yourdomain.com'+req.url)
});
Had the same problem a few days ago, and this GitHub issue helped:
https://github.com/techpines/express.io/issues/17#issuecomment-26191447
Your code is on the right way, it just need some changes. The code below is a slightly modified version of the snippet you provided.
var fs = require('fs'),
express = require('express.io');
options = {
ca : fs.readFileSync('./ssl/site.com.pem'),
key: fs.readFileSync('./ssl/site.com.key'),
cert: fs.readFileSync('./ssl/site_com.crt')
};
var app = express();
app.https(options).io();
var httpServer = require('http').createServer(app);
// ...
app.listen(443);
express.io.listen(httpServer);
httpServer.listen(80, function() { }, function() { });

expressjs 4.x and https, generate key and certificate

I want to create an https server with express 4.x. Even if a lot of code found on google is based on express 3.x I think I made the port correctly.
Even if I tried to goole it is not very clear to me how to generate the keys. Without the key I'm expecting 401.
I tried with the script found in this gist. But I'm keeping on receiving the error Error: DEPTH_ZERO_SELF_SIGNED_CERT.
I'd like to test it both with curl, request, and super test.
This is what actually I have:
server.js
var express = require('express')
, https = require('https')
, fs = require('fs');
var privateKey = fs.readFileSync('./server/server-private-key.pem').toString();
var certificate = fs.readFileSync('./server/server-certificate.pem').toString();
var options = {
key : privateKey
, cert : certificate
}
var app = express();
app.get('/', function(req, res) {
req.client.authorized ?
res.json({"status":"approved"}) :
res.json({"status":"denied"}, 401);
});
server = https.createServer(options,app);
var port = 12345;
server.listen(port, function(){
console.log("Express server listening on port " + port);
});
client.js
var https = require('https');
var fs = require('fs');
var options = {
host: 'localhost',
port: 12345,
method: 'GET',
path: '/',
key: fs.readFileSync('./client/client-private-key.pem'),
cert: fs.readFileSync('./client/client-certificate.pem'),
headers: {}
};
var req = https.request(options, function(res) {
console.log('dudee');
console.log(res);
});
req.end();
With cURL you can use the -k flag to bypass the self-signed cert problem.
With request you can just set rejectUnauthorized: false in the request options.

How do I setup a SSL certificate for an express.js server?

Before, in an older version of express, I could do this:
express.createServer({key:'keyFile', cert:'certFile'});
However, in newer versions of express this no longer works:
var app = express();
Should I call app.use() to set the certs? If so how?
See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):
var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );
https.createServer({
key: privateKey,
cert: certificate
}, app).listen(port);
Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
I was able to get SSL working with the following boilerplate code:
var fs = require('fs'),
http = require('http'),
https = require('https'),
express = require('express');
var port = 8000;
var options = {
key: fs.readFileSync('./ssl/privatekey.pem'),
cert: fs.readFileSync('./ssl/certificate.pem'),
};
var app = express();
var server = https.createServer(options, app).listen(port, function(){
console.log("Express server listening on port " + port);
});
app.get('/', function (req, res) {
res.writeHead(200);
res.end("hello world\n");
});
This is my working code for express 4.0.
express 4.0 is very different from 3.0 and others.
4.0 you have /bin/www file, which you are going to add https here.
"npm start" is standard way you start express 4.0 server.
readFileSync() function should use __dirname get current directory
while require() use ./ refer to current directory.
First you put private.key and public.cert file under /bin folder,
It is same folder as WWW file.
no such directory found error:
key: fs.readFileSync('../private.key'),
cert: fs.readFileSync('../public.cert')
error, no such directory found
key: fs.readFileSync('./private.key'),
cert: fs.readFileSync('./public.cert')
Working code should be
key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
Complete https code is:
const https = require('https');
const fs = require('fs');
// readFileSync function must use __dirname get current directory
// require use ./ refer to current directory.
const options = {
key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
};
// Create HTTPs server.
var server = https.createServer(options, app);

Resources