Authentication using HTTPS client certificates

Image from
const express = require('express')
const fs = require('fs')
const https = require('https')

Setting up the private key and the certificate

$ openssl req -x509 -newkey rsa:4096 -keyout server_key.pem -out server_cert.pem -nodes -days 365 -subj "/CN=localhost/O=Client\ Certificate\ Demo"

Configuring the Node.js HTTP server

const opts = { key: fs.readFileSync('server_key.pem')
, cert: fs.readFileSync('server_cert.pem')
, requestCert: true
, rejectUnauthorized: false
, ca: [ fs.readFileSync('server_cert.pem') ]
const app = express()
app.get('/', (req, res) => {
res.send('<a href="authenticate">Log in using client certificate</a>')
app.get('/authenticate', (req, res) => {
const cert = req.connection.getPeerCertificate()
if (req.client.authorized) {
res.send(`Hello ${cert.subject.CN}, your certificate was issued by ${cert.issuer.CN}!`)
} else if (cert.subject) {
.send(`Sorry ${cert.subject.CN}, certificates from ${cert.issuer.CN} are not welcome here.`)
} else {
.send(`Sorry, but you need to provide a client certificate to continue.`)
https.createServer(opts, app).listen(9999)

Setting up client certificates

$ openssl req -newkey rsa:4096 -keyout alice_key.pem -out alice_csr.pem -nodes -days 365 -subj "/CN=Alice"
$ openssl req -newkey rsa:4096 -keyout bob_key.pem -out bob_csr.pem -nodes -days 365 -subj "/CN=Bob"
$ openssl x509 -req -in alice_csr.pem -CA server_cert.pem -CAkey server_key.pem -out alice_cert.pem -set_serial 01 -days 365
$ openssl x509 -req -in bob_csr.pem -signkey bob_key.pem -out bob_cert.pem -days 365

Trying to get in

$ openssl pkcs12 -export -clcerts -in alice_cert.pem -inkey alice_key.pem -out alice.p12
$ openssl pkcs12 -export -in bob_cert.pem -inkey bob_key.pem -out bob.p12
$ curl --insecure --cert bob.p12 --cert-type p12 https://localhost:9999/authenticate




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store