Last active
August 9, 2022 21:09
-
-
Save ceejbot/4479925 to your computer and use it in GitHub Desktop.
A node https server/client pair that uses client certs to authorize clients.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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