Skip to content

Instantly share code, notes, and snippets.

@michalc
Last active September 21, 2021 05:44
Show Gist options
  • Save michalc/b3f03e9234a2916810af12fa1d6c44af to your computer and use it in GitHub Desktop.
Save michalc/b3f03e9234a2916810af12fa1d6c44af to your computer and use it in GitHub Desktop.
Postman pre-request script for Hawk authentication in custom header
/*****************************************************************************/
const hawkId = pm.variables.get('hawk_id');
const hawkKey = pm.variables.get('hawk_key');
const hawkHeader = pm.variables.get('hawk_header') || 'authorization';
/*****************************************************************************/
const timestamp = parseInt(new Date().getTime() / 1000);
const nonce = CryptoJS.enc.Base64.stringify(CryptoJS.lib.WordArray.random(6));
const url = pm.request.url;
const port = url.port || (url.protocol == 'https' && 443) || 80;
const canonicalPayload = `` +
`hawk.1.payload\n${pm.request.headers.get('content-type')}\n${request.data}\n`;
const hash = CryptoJS.enc.Base64.stringify(CryptoJS.SHA256(canonicalPayload));
const canonicalRequest = `` +
`hawk.1.header\n${timestamp}\n${nonce}\n${request.method}\n${url.getPathWithQuery()}\n` +
`${url.getHost()}\n${port}\n${hash}\n\n`;
const mac = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(canonicalRequest, hawkKey));
pm.request.headers.add({
key: hawkHeader,
value: `` +
`Hawk mac="${mac}", hash="${hash}", id="${hawkId}", ` +
`ts="${timestamp}", nonce="${nonce}"`
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment