-
-
Save dipendra-sharma/dd07b1d67ab158acea19f498c42556da to your computer and use it in GitHub Desktop.
Axios SSL Certificate Pinning
This file contains hidden or 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