-
-
Save itsdevsunny/3f9872cef6d44a2c832e99bbc206df3a to your computer and use it in GitHub Desktop.
Axios SSL Certificate Pinning
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
const tls = require('tls'); | |
const https = require('https'); | |
const crypto = require('crypto'); | |
const axios = require('axios'); | |
function sha256(s) { | |
return crypto.createHash('sha256').update(s).digest('base64'); | |
} | |
const options = { | |
rejectUnauthorized: true, | |
checkServerIdentity: function(host, cert) { | |
// Make sure the certificate is issued to the host we are connected to | |
const err = tls.checkServerIdentity(host, cert); | |
if (err) { | |
return err; | |
} | |
// Pin the public key, similar to HPKP pin-sha25 pinning | |
const pubkey256 = 'ORH27mxcLwxnNpR7e0i6pdDPWLXdpeWgr5bEfFVbxW8='; | |
if (sha256(cert.pubkey) !== pubkey256) { | |
return new Error('Certificate verification error'); | |
} | |
// OR Pin the exact certificate, rather than the pub key | |
const cert256 = '3A:AE:0A:71:39:2F:86:22:5E:F2:9F:A9:FE:0C:66:BD:' + | |
'8A:85:AB:F5:C6:8F:F2:D1:E3:33:A8:EF:6F:EB:52:87'; | |
if (cert.fingerprint256 !== cert256) { | |
return new Error('Certificate verification error'); | |
} | |
}, | |
}; | |
const agent = new https.Agent(options); | |
axios.get('https://api.github.com', { httpsAgent: agent }) | |
.then(response => { | |
console.log('All OK. Server matched our pinned cert or public key') | |
}) | |
.catch(error => { | |
console.error(error.message) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment