Skip to content

Instantly share code, notes, and snippets.

@thetminko
Forked from arvindkumarbadwal/axios.js
Created November 15, 2023 05:36
Show Gist options
  • Save thetminko/47bccb182982762181fcc5dd43217fe7 to your computer and use it in GitHub Desktop.
Save thetminko/47bccb182982762181fcc5dd43217fe7 to your computer and use it in GitHub Desktop.
Axios SSL Certificate Pinning
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