Last active
August 30, 2024 21:22
-
-
Save antonioshadji/7e0a17c240544ff5335909ed4f53bf01 to your computer and use it in GitHub Desktop.
Postman pre-request code that works with localhost server to include signed header in request
This file contains hidden or 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
// This script reqires a local server to be running at localhost:3000 | |
// to handle the cryptographic signature. | |
// store your signing key in your enviroment | |
const signingKey = pm.environment.get("signing_key"); | |
// javascript Date.now() returns unix timestamp in ms, convert to s | |
const timestamp = Math.floor(Date.now() / 1000) | |
const method = pm.request.method.toString(); | |
// Postman does not substitute URL parameters before running this script | |
// this line performs the variable substitution | |
pm.collectionVariables.values.substitute(pm.request.url, null, true) | |
const path = '/api' + pm.request.url.getPath() | |
if (pm.request.body.raw) { | |
// remove all spaces from body THIS IS REQUIRED | |
pm.request.body.raw = pm.request.body.raw.replace(/\s/g, '') | |
var message = `${timestamp}${method}${path}${pm.request.body.raw}`; | |
} else { | |
var message = `${timestamp}${method}${path}`; | |
} | |
try { | |
const response = await pm.sendRequest({ | |
url: "http://localhost:3000", | |
method: "POST", | |
header: { | |
'Content-Type': 'application/json', | |
'Accept': 'application/json' | |
}, | |
body: { | |
mode: 'raw', | |
raw: JSON.stringify({ | |
m: message, | |
pkey: signingKey, | |
}) | |
} | |
}); | |
var jsonResponse = response.json() | |
pm.request.headers.add({ | |
key: 'x-timestamp', | |
value: timestamp | |
}); | |
pm.request.headers.add({ | |
key: 'x-signature', | |
value: jsonResponse.s | |
}); | |
} catch (err) { | |
if (err.code === 'ECONNREFUSED') { | |
console.error( | |
"Please ensure you have a signature server running on localhost:3000" | |
) | |
} | |
console.error(err.message); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment