Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NODE JS example of creating a HTTP Authentication: MAC Access Authentication with SHA-256
/* NODE JS example of creating a HTTP Authentication: MAC Access Authentication with SHA-256
* https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00
*/
const crypto = require('crypto');
const baseURL = 'https://example.com';
const serverId = 'SERVER-PROVIDED-ID';
const secretKey = 'SUPER-SECRET-BASE64-KEY';
const issuedKeyAt = 1557794619;
const randomString = 'WINTERBOOTS';
function createBase64Hash(data, hashAlg = 'sha256') {
return crypto
.createHash(hashAlg)
.update(data)
.digest('base64');
}
function createHMACBase64Hash(data, hashAlg = 'sha256') {
return crypto
.createHmac(hashAlg, Buffer.from(secretKey, 'base64'))
.update(data)
.digest('base64');
}
function getEpochSinceIssued() {
const currentEpochDate = Math.floor(new Date().getTime() / 1000.0);
return currentEpochDate - issuedKeyAt;
}
function createHMACAuth(domain, route, method, payload) {
const hostname = domain.replace('https://', '');
const secondsSinceIssued = getEpochSinceIssued();
const bodyHash = createBase64Hash(JSON.stringify(payload));
const nonce = `${secondsSinceIssued}:${randomString}`;
const macString = `${nonce}\=${method}\n${route}\n${hostname}\n443\n${bodyHash}\n\n`;
const mac = createHMACBase64Hash(macString);
return `MAC id='${serverId}',nonce='${nonce}',bodyhash='${bodyHash}',mac='${mac}'`;
}
const newUser = {
email: 'helloworld@example.com',
password: 'H-MAC-KING',
};
const macAuth = createHMACAuth(baseURL, '/users', 'POST', newUser);
console.log({
headers: {
Authorization: macAuth,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.