Skip to content

Instantly share code, notes, and snippets.

@mildronize
Forked from ceejbot/secure-client.js
Created October 26, 2021 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mildronize/1bc038f065114b48638c727c8fa2e3ab to your computer and use it in GitHub Desktop.
Save mildronize/1bc038f065114b48638c727c8fa2e3ab to your computer and use it in GitHub Desktop.
A node https server/client pair that uses client certs to authorize clients.
#!/usr/bin/env node
var fs = require('fs'),
https = require('https');
// We pass our client key & cert to the http agent,
// which we then use to make the request.
var agentOptions = {
key: fs.readFileSync('client.key'),
cert: fs.readFileSync('client.crt'),
};
var agent = new https.Agent(agentOptions)
var requestOptions = {
host: 'localhost',
port: 8000,
path: '/',
method: 'GET',
agent: agent,
ca: fs.readFileSync('ca.crt') // Because we've self-signed our server cert
// we need an authority chain for it.
};
var req = https.request(requestOptions, function (res)
{
console.log('got a response');
res.pipe(process.stdout);
});
req.end();
req.on('error', function (err)
{
console.error(err);
});
#!/usr/bin/env node
var fs = require('fs'),
https = require('https');
var options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt'),
ca: fs.readFileSync('ca.crt'), // authority chain for the clients
requestCert: true, // ask for a client cert
rejectUnauthorized: false, // act on unauthorized clients at the app level
};
var server = https.createServer(options, function(req, res) {
console.log('responding to request')
res.end('welcome!\n');
})
server.on('connection', function(c)
{
console.log('insecure connection')
});
server.on('secureConnection', function (c)
{
// c.authorized will be true if the client cert presented validates with our CA
console.log('secure connection; client authorized: ', c.authorized);
});
server.listen(8000, function() {
console.log('server listening on port 8000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment