Skip to content

Instantly share code, notes, and snippets.

@caseyjkey
Created June 16, 2020 16:51
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 caseyjkey/8c6ade98ffc8abc0a45b2946cd279c74 to your computer and use it in GitHub Desktop.
Save caseyjkey/8c6ade98ffc8abc0a45b2946cd279c74 to your computer and use it in GitHub Desktop.
Server-side client-certificate authorization
const express = require('express')
const fs = require('fs')
const https = require('https')
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) => {
const cert = req.connection.getPeerCertificate()
if (req.client.authorized) {
res.json({ message: `Hello ${cert.subject.CN}, your certificate was issued by ${cert.issuer.CN}!`})
} else if (cert.subject) {
res.status(403)
.json({ message: `Sorry ${cert.subject.CN}, certificates from ${cert.issuer.CN} are not welcome here.`})
} else {
res.status(401)
.json({ message: `Sorry, but you need to provide a client certificate to continue.`})
}
})
https.createServer(opts, app).listen(9999)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment