Skip to content

Instantly share code, notes, and snippets.

@hadibadjian
Last active September 16, 2020 08:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadibadjian/7185362a1ee3fa71b46ea90f8ca9c088 to your computer and use it in GitHub Desktop.
Save hadibadjian/7185362a1ee3fa71b46ea90f8ca9c088 to your computer and use it in GitHub Desktop.
Postman HMAC Authorization

Postman HMAC Authorization

This setup automatically constructs the HMAC value and populates it in the request header.

Create a key value entry in Headers section to retrieve Authorization value from environment variable authorization.

Imgur

Add pre-request-script file content to Pre-request Script section.

This script calculates the HMAC value based on applicationId, applicationSecret, and hmacAlgorithm environment variables.

Possible options for hmacAlgorithm are HMAC-SHA1, HMAC-SHA256 and HMAC-SHA512.

Imgur

Imgur

Modify authorization template variable based on your application authorization format.

// inspired by https://gist.github.com/DinoChiesa/75796b27828cf8e15c91
function calculateHMAC(config, messageDictionary) {
var template = 'AppAuth method=${algorithm} applicationId=${applicationId} signature=${signature}';
var hashf = (function() {
switch (config.algorithm) {
case 'HMAC-SHA1': return CryptoJS.HmacSHA1;
case 'HMAC-SHA256': return CryptoJS.HmacSHA256;
case 'HMAC-SHA512': return CryptoJS.HmacSHA512;
default : return null;
}
}());
// construct message to be hashed
var message = '';
config.headers.forEach(function(h) {
if(message !== '') { message += '\n'; }
message += messageDictionary[h];
});
var hash = hashf(message, config.secretkey);
var signatureOptions = {
algorithm: config.algorithm,
applicationId: config.applicationId,
signature : CryptoJS.enc.Base64.stringify(hash)
};
// construct Authorization header value
var authorization = template;
Object.keys(signatureOptions).forEach(function(key) {
var pattern = "${" + key + "}";
var value = (typeof signatureOptions[key] != 'string') ? signatureOptions[key].join(' ') : signatureOptions[key];
authorization = authorization.replace(pattern, value);
});
return authorization;
}
var targetUrl = request.url.trim().replace(new RegExp('^https?://[^/]+/'),'/');
var messageDictionary = { url: targetUrl };
var config = {
algorithm : environment['hmacAlgorithm'],
applicationId: environment['applicationId'],
secretkey : environment['applicationSecret'],
headers: ['url']
};
var authorization = calculateHMAC(config, messageDictionary);
postman.setEnvironmentVariable('authorization', authorization);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment