Note that when I wrote this jQuery was built into Postman. Since v4.5.0 it has been replaced by CheerioJS and Lodash, so this solution won’t work with v4.5.0+.

I successfully got custom SHA256 header signing in Postman working using Pre-request script. Here’s how I did it:

Per the Postman documentation, you can’t set request headers directly. In the pre-request script you have to assign the header value to a global or environment variable, and then use the header variable in the header key-value editor.

Here’s an example of using environment variables in Headers:

enter image description here

Here’s the pre-request script I wrote to generate the values needed, and assign to the header variables:

var key = 'my__key';
var base64Secret = 'my_b64_secret';

function newGuid() {
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : r & 0x3 | 0x8; return v.toString(16); });
}

function epochTime() {
    var d = new Date();
    var t = d.getTime();
    var o = t + "";
    return o.substring(0, 10);
}

// Load required 3rd party JS libs via jQuery
// http://stackoverflow.com/a/11803418

$.when(
    $.getScript( "https://cdnjs.cloudflare.com/ajax/libs/jsSHA/2.0.1/sha256.js" ),
    $.getScript( "https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/md5.js" ),
    $.getScript( "https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/enc-base64-min.js" ),
    $.Deferred(function( deferred ){
        $( deferred.resolve );
    })
).done(function(){

    var time = epochTime();
    var nonce = newGuid();
    var method = request.method;
    var encodedUri = encodeURIComponent(request.url).toLowerCase();

    // Build the request body string from the Postman request.data object
    var requestBody = "";
    var firstpass = true;
    for(var param in request.data)
    {
        if(!firstpass){
            requestBody += "&";
        }
        requestBody += param + "=" + request.data[param];
        firstpass = false;
    }

    var b64BodyContent = "";
    if(requestBody){
        // MD5 hash and convert the request body string to base 64
        b64BodyContent = CryptoJS.MD5(requestBody).toString(CryptoJS.enc.Base64);
    }

    var rawSignature = key + method + encodedUri + time + nonce + b64BodyContent;

    // Generate HMAC SHA256 signature
    // Using library: http://caligatio.github.io/jsSHA/
    var shaObj = new jsSHA("SHA-256", "TEXT");
    shaObj.setHMACKey(base64Secret, "B64");
    shaObj.update(rawSignature);
    var signature = shaObj.getHMAC("B64");

    postman.setEnvironmentVariable('key', key);
    postman.setEnvironmentVariable('time', time);
    postman.setEnvironmentVariable('nonce', nonce);
    postman.setEnvironmentVariable('signature', signature);
});



Source link https://sqa.stackexchange.com/questions/11777/--api-with--hmac-

LEAVE A REPLY

Please enter your comment!
Please enter your name here