Created
April 27, 2017 18:05
-
-
Save ravikiranj/d056216c0cee8cdbbdd1336ec227d6f6 to your computer and use it in GitHub Desktop.
HMAC SHA512 Authentication Pre-request script for Postman
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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'])); |
cool
Great work, Thank you ! 🤗
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
saved my life today, thanks!