Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dylansm/0e27fd6b0e4c5e94e099b85c694d237e to your computer and use it in GitHub Desktop.
Save dylansm/0e27fd6b0e4c5e94e099b85c694d237e to your computer and use it in GitHub Desktop.
HMAC SHA512 Authentication Pre-request script for Postman
/* Pre-requisite
==================
1) Create an Environment (if you don't already have on) and enable it for your request
2) Add a new Header with key as "Authorization" and value as "{{hmacAuthHeader}}"
3) Add the following Pre-request Script that computes the hmacAuthHeader variable and adds it to the environment
4) Fill your CLIENT_KEY and SECRET_KEY with valid values
*/
function getPath(url) {
var pathRegex = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var result = url.match(pathRegex);
return result && result.length > 1 ? result[1] : '';
}
function getQueryString(url) {
var arrSplit = url.split('?');
return arrSplit.length > 1 ? url.substring(url.indexOf('?')+1) : '';
}
function getAuthHeader(httpMethod, requestUrl, requestBody) {
var CLIENT_KEY = 'REPLACE_WITH_YOUR_CLIENT_KEY';
var SECRET_KEY = 'REPLACE_WITH_YOUR_SECRET_KEY';
var AUTH_TYPE = 'HMAC-SHA512';
var requestPath = getPath(requestUrl);
var queryString = getQueryString(requestUrl);
if (httpMethod == 'GET' || !requestBody) {
requestBody = '';
} else {
requestBody = JSON.stringify(requestBody);
}
var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(requestBody));
var timestamp = new Date().toISOString().split('.')[0]+"Z";
var requestData = [httpMethod, requestPath, queryString, timestamp, hashedPayload].join("\n");
var hashedRequestData = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(requestData));
var hmacDigest = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA512(hashedRequestData, SECRET_KEY));
var authHeader = AUTH_TYPE + ' timestamp=' + timestamp + ", client=" + CLIENT_KEY + ', signature=' + hmacDigest;
return authHeader;
}
postman.setEnvironmentVariable('hmacAuthHeader', getAuthHeader(request['method'], request['url'], request['data']));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment