Skip to content

Instantly share code, notes, and snippets.

@ceejbot ceejbot/secure-client.js
Last active Dec 10, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.