Skip to content

Instantly share code, notes, and snippets.

@sehmbimanvir
Created February 21, 2020 18:21
Show Gist options
  • Save sehmbimanvir/0d5d96db38500d71051bdb0fb278b4f6 to your computer and use it in GitHub Desktop.
Save sehmbimanvir/0d5d96db38500d71051bdb0fb278b4f6 to your computer and use it in GitHub Desktop.
Postman Pre-Request to Generate HMAC256
/** Import Required Libraries */
const uuidInstance = require('uuid');
const cryptoJs = require('crypto-js');
/** Get Postman Local Varialbes */
const secretKey = pm.variables.get('secretKey');
const appId = pm.variables.get('appId');
const baseUrl = pm.variables.get('baseUrl');
/** Check if any required variable is missing then throw Error. */
if (!secretKey || !appId || !baseUrl) {
throw new Error('One of the following variable is missing | secretKey, appId, baseUrl');
}
/** Collect Request Data (Method, Current URI) */
const requestPath = pm.request.url.getPath().toLowerCase();
const requestMethod = pm.request.method.toLowerCase();
const requestUrl = baseUrl + requestPath;
/** Generate UUID and Timestamp */
const nonce = uuidInstance.v4();
const timeStamp = Date.now();
/** Generate Hash and Encode using Base64 */
const hashInBase64 = encryptString(appId, requestMethod, requestUrl, timeStamp, nonce);
/** Create and set Authentication Header */
const authHeader = getAuthorizationHeader(appId, hashInBase64, timeStamp, nonce);
pm.globals.set('authHeader', authHeader);
/** Return Authorization Header */
function getAuthorizationHeader (...params) {
return params.join(':');
}
/** Encrypt String using HMACSHA256 Algo */
function encryptString (...params) {
return btoa(cryptoJs.HmacSHA256(params.join(''), secretKey));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment