Jaie
Jaie

Reputation: 117

POSTMAN Pre-Request Script Need Actual Body for Hashmac calculation

I have googled and looked for this answer but been unable to find what I need

During the pre-request script I do a hashmac calculation which requires the body to actually match what postman sends.

This is normally fine until people start using enviroment variables and comments in their json body’s.

I can easily fix the json body for enviroment variables using

requestBody = pm.variables.replaceIn(requestBody);
hashedPayload = CryptoJS.enc.Base64.stringify(CryptoJS.MD5(CryptoJS.enc.Utf8.parse(requestBody)));


// I then set the Enviroment header for the hashmac
postman.setEnvironmentVariable('hmacAuthHeader', getAuthHeader(request['method'], requestUrl, request['data']));

However comments seem to be a bit more tricky.

I am wondering if anyone knows how to get the actual request body that gets sent in a post after it has had all the comments and enviroment variables replaced and removed during a pre-request script.

Thanks in advance. Cheers

Upvotes: 0

Views: 158

Answers (1)

Jaie
Jaie

Reputation: 117

Postman provided answer here: https://community.postman.com/t/pre-request-script-need-actual-body-for-hashmac-calculation/57022/6 I used:

 var requestBody =  pm.request.body.toString();
 // We need to ensure that all variables are 
 //replaced before we hash the values otherwise they wont match
 requestBody = pm.variables.replaceIn(requestBody);
 // Strip JSON Comments
 if (pm.request.body.mode === 'raw') {
        requestBody = requestBody.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" : m)
        pm.request.body.raw = requestBody;
        pm.request.headers.add({key: 'Content-Type', value: 'application/json'});
    }
    

const hashedPayload = CryptoJS.enc.Base64.stringify(CryptoJS.MD5(CryptoJS.enc.Utf8.parse(requestBody)));

Upvotes: 0

Related Questions