Skip to content

Instantly share code, notes, and snippets.

@antonioperez
Created July 29, 2019 01:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonioperez/2c17117eb34bf8d6c2a1be05155699a4 to your computer and use it in GitHub Desktop.
Save antonioperez/2c17117eb34bf8d6c2a1be05155699a4 to your computer and use it in GitHub Desktop.
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