Skip to content

Instantly share code, notes, and snippets.

@achesco
Last active February 20, 2019 15:35
Show Gist options
  • Save achesco/ad60565d9036e1dc023d8768be2d4ddb to your computer and use it in GitHub Desktop.
Save achesco/ad60565d9036e1dc023d8768be2d4ddb to your computer and use it in GitHub Desktop.
Server and client SSL certificates

CNs are important!!! -days 3650

Create server key and cert (server_key.pem, server_cert.pem)

openssl req -x509 -newkey rsa:4096 -keyout server_key.pem -out server_cert.pem -nodes -days 3650 -subj "/CN=localhost"

Create client key and cert signing request (admin_key.pem, admin_csr.pem)

openssl req -newkey rsa:4096 -keyout admin_key.pem -out admin_csr.pem -nodes -days 3650 -subj "/CN=admin"

Sign client's cert with server key (admin_cert.pem)

openssl x509 -req -in admin_csr.pem -CA server_cert.pem -CAkey server_key.pem -out admin_cert.pem -set_serial 01 -days 3650

Bundle client cert to be used in browser (admin.p12)

openssl pkcs12 -export -clcerts -in admin_cert.pem -inkey admin_key.pem -out admin.p12

Import admin.p12 to keychain (OS X)

security import admin.p12

Setting up NodeJs server

TLS options:

{
  key: fs.readFileSync('server_key.pem'),
  cert: fs.readFileSync('server_cert.pem'),
  ca: [ fs.readFileSync('server_cert.pem') ],
  requestCert: true,
  rejectUnauthorized: false, // true to reject, false to handle (i.g. show error message)
}

Request handling:

(req, res) => {
 	const cert = req.connection.getPeerCertificate();
	if (req.client.authorized) {
		res.send(` ${cert.subject.CN} issued by ${cert.issuer.CN} is valid`);
	} else if (cert.subject) {
		res.status(403).send(`${cert.subject.CN} issued by ${cert.issuer.CN} is not valid`);
	} else {
		res.status(401).send('Certificate is not provided')
	}
}

Test with curl

curl --insecure --cert admin.p12:password --cert-type p12 https://localhost/auth
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment