Last active
January 20, 2021 11:01
-
-
Save ranggasama/82b2f3f26f37b91a496ec8c7edd6c7ed to your computer and use it in GitHub Desktop.
Sample NodeJs application to send HMAC authentication
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 https = require('https'); | |
const fs = require('fs'); | |
const crypto = require('crypto'); | |
const data = JSON.stringify({ | |
foo: 'bar' | |
}), | |
path = '/ok', | |
method = 'POST'; | |
// process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0; | |
const url = 'localhost', | |
username = 'hmac-user', | |
secret = '~,6a=HFaC/P]R5Zp', | |
uuid = '9b83f786-5a70-11eb-ae93-0242ac130002', | |
algorithm = 'hmac-sha256'; | |
let authorization, digestBodyHeader, dateFormat, signingString, signature; | |
dateFormat = new Date().toUTCString(); | |
digestBodyHeader = 'SHA-256=' + crypto.createHash('sha256').update(data).digest('base64'); | |
signingString = 'x-date: ' + dateFormat + '\n' + method + ' ' + path + ' HTTP/1.1' + '\n' + 'x-uuid: ' + uuid + '\n' + 'digest: ' + digestBodyHeader; | |
signature = crypto.createHmac('sha256', secret).update(signingString).digest('base64'); | |
authorization = 'hmac username="' + username + '", algorithm="' + algorithm + '", headers="x-date request-line x-uuid digest", signature="' + signature + '"'; | |
console.log('variables:\n', | |
'url:', url, '\n', | |
'username:', username, '\n', | |
'secret:', secret, '\n', | |
'body:', data, '\n', | |
'signingString:', signingString, '\n', | |
'signature:', signature, '\n', | |
'authorization:', authorization); | |
const options = { | |
hostname: url, | |
port: 443, | |
path: path, | |
method: method, | |
ca: [fs.readFileSync('/usr/local/share/ca-certificates/CACert.crt')], | |
headers: { | |
'Digest': digestBodyHeader, | |
'Authorization': authorization, | |
'X-Date': dateFormat, | |
'X-UUID': uuid, | |
'Content-Type': 'application/json', | |
'Content-Length': data.length | |
} | |
}; | |
const req = https.request(options, res => { | |
console.log(`response header: ${JSON.stringify(res.headers, null, " ")}`); | |
res.on('data', d => { | |
process.stdout.write(d) | |
}) | |
}); | |
req.on('error', error => { | |
console.error(error) | |
}); | |
req.write(data); | |
console.log('request:', req._header); | |
req.end(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment