Quantcast
Channel: Loutilities
Viewing all articles
Browse latest Browse all 17

Using SSL Self Signed Certs with Node.js

$
0
0

If you plan to proxy sites or services that are SSL enabled and are signed with self-signed certs, then you need to be aware that you have to configure a few extra parameters to make sure the SSL handshake happens properly. Otherwise, the request goes through without validating the self-signed certs (which is a strange default behavior IMO).

Namely, you have to do the following:

  1. Use the https module (API docs here)
  2. Set the agent to false (unless you plan to provide one)
  3. Set the ca to the location where the self-signed cert is located respective to your node file
  4. Set the rejectUnauthorized to true so that an error is emitted upon failure

Here is a snippet of code that you can use as an example:

var https = require('https'),
        fs = require('fs'),
        host = 'localhost',
        port = 443;

    exports.getTest = function (req, res, next) {
        var url = '/login.html';

        processRequest(req, res, next, url);
    };

    function processRequest (req, res, next, url) {
        var httpOptions = {
            hostname: host,
            path: url,
            port: port,
            method: 'GET',
            agent: false,
            ca: [fs.readFileSync('ssl/myroot_cert.crt')],
            rejectUnauthorized: true
        };

        var reqGet = https.request(httpOptions, function (response) {
            var content = '';
            response.on('data', function (chunk) {
                content += chunk;
            });
            response.on('end', function () {
                try {
                        res.send("Successful SSL Handshake");
                }
                catch (e) {
                    res.send(500);
                }
            });
        });

        reqGet.on('error', function (e) {
            res.send("Unable to SSL Handshake", 401);
        });

        reqGet.end();

        return next();
    }


Viewing all articles
Browse latest Browse all 17

Trending Articles