diff --git a/examples/ssl/.gitignore b/examples/ssl/.gitignore new file mode 100644 index 00000000000..737c7a05494 --- /dev/null +++ b/examples/ssl/.gitignore @@ -0,0 +1 @@ +**/*.pem diff --git a/examples/ssl/Readme.md b/examples/ssl/Readme.md new file mode 100644 index 00000000000..f736de45cb6 --- /dev/null +++ b/examples/ssl/Readme.md @@ -0,0 +1,14 @@ +# Express server with SSL enabled + +Please create the self-signed certificate and private key to path `/certs` by following command: + +```bash +./create_certs.sh +``` + +When running this example, the application runs on + +* https://localhost:8443 + +and asks the user to make a security exception in the browser in order to see the pages. +CAUTION: *Self-signed certificates should never be used in production environments!* diff --git a/examples/ssl/create_certs.sh b/examples/ssl/create_certs.sh new file mode 100755 index 00000000000..fb943f2e378 --- /dev/null +++ b/examples/ssl/create_certs.sh @@ -0,0 +1,5 @@ +#!/bin/bash + +mkdir -p certs && \ +cd certs && \ +openssl req -x509 -newkey rsa:4096 -nodes -sha256 -subj '/CN=localhost' -days 3650 -keyout key.pem -out cert.pem diff --git a/examples/ssl/index.js b/examples/ssl/index.js new file mode 100644 index 00000000000..8cad4aa92ec --- /dev/null +++ b/examples/ssl/index.js @@ -0,0 +1,41 @@ +/** + * Module dependencies. + */ + +var express = require('../..'); +var fs = require('fs'); +var path = require('path'); +var https = require('https'); + +var app = module.exports = express(); + +app.use(function(req, res) { + res + .set('Content-Type', 'text/html;charset=utf-8') + .status(200) + .send('

Hello world from a SSL-enabled server!

') + .end(); +}); + +/* istanbul ignore next */ +if (!module.parent) { + try { + /* These certificates should be created manually as specified in the + * Readme.md */ + var certsPath = path.join(__dirname, 'certs'); + var options = { + key: fs.readFileSync(path.join(certsPath, 'key.pem')), + cert: fs.readFileSync(path.join(certsPath, 'cert.pem')) + }; + + /* Instead of using app.listen() directly, you should create a regular + * Node.js HTTPS server and place the Express server as its only midware. */ + var httpsServer = https.createServer(options, app); + var PORT = 8443; + httpsServer.listen(PORT, function() { + console.log('SSL Express server responds in https://localhost:' + PORT); + }); + } catch(er) { + console.error('Please create the certificates manually first according to the Readme.md.'); + } +}