Ensure same Guids and IsoTimeStamps pre and post request

Assume that I need to POST a raw json body containing a random {{$guid}} and the current {{$isoTimestamp}}.

Assume also that I need to hash that very same body using e.g. CryptoJS.MD5() as part of a larger HMAC authentication scheme where the remote API will also perform the same MD5 hash and compare it to the hash of the incoming request.

Given that I can use pm.variables.replaceIn(pm.request.body) to “resolve” both the {{$guid}} and the {{$isoTimestamp}} in the pre-request script, and use the result to generate the MD5 hash, how can I ensure that the exact same {{$guid}} and {{$isoTimestamp}} that are used in the pre-request script are also used in the actual request?

Right now, it seems Postman (v8) just generates another {{$guid}} and {{$isoTimestamp}}, which of course makes the authentication fail due to different MD5 hashes.

Hi @qfyra, Welcome to the community!

A better way would be to save the random values to environment/globals/collection variables and use them later in the request body.

In the below example, I have assigned the values to global variables in the pre-request script.

const c_guid=pm.variables.replaceIn("{{$guid}}");

pm.globals.set("c_guid",c_guid);

const c_isotimestamp=pm.variables.replaceIn("{{$isoTimestamp}}");

pm.globals.set("c_isotimestamp",c_isotimestamp);

console.log(pm.variables.replaceIn(pm.request.body));

console.log(c_guid);

console.log(c_isotimestamp);

Once the above variables are set, they will not change and the postman will not override the random values.

Hope this helps :slight_smile:

2 Likes

Very good, thank you. I ended up doing this in the pre-request script:

var randomGuid = pm.variables.replaceIn("{{$guid}}");
var dateTimeNow = pm.variables.replaceIn("{{$isoTimestamp}}");
var aYearFromNow = new Date();
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);
pm.variables.set("randomGuid", randomGuid);
pm.variables.set("dateTimeNow", dateTimeNow);
pm.variables.set("aYearFromNow", aYearFromNow.toISOString());

if (pm.request.body && !pm.request.body.isEmpty()) {
    var body = pm.variables.replaceIn(pm.request.body);
    var md5 = CryptoJS.MD5(body.toString());

And this in the Postman request body:

{
   "Name": "PM Test {{randomGuid}}",
   "StartDate": "{{dateTimeNow}}",
   "SubscriptionExpiryDate": "{{aYearFromNow}}"
}

Seems to be working as I intended. I get a new guid and new datetimes per request, and it is the same guid and timestamps that are used for the MD5 hash.

All good.

1 Like