Sign API requests with HMAC in a pre-request script
Exchanges, payment providers and internal service meshes often skip bearer tokens and ask for a signature instead: the client hashes the request with a shared secret, and the server does the same and compares. A stolen signature is useless a few minutes later, and the secret never travels over the wire.
The scheme differs from API to API, but the parts are always the same, and a pre-request script can build them.
A typical scheme
Say the API documents:
string_to_sign = METHOD + "\n" + PATH_WITH_QUERY + "\n" + TIMESTAMP + "\n" + SHA256_HEX(BODY)
signature = BASE64(HMAC_SHA256(secret, string_to_sign))
Headers:
X-Api-Key: <key id>
X-Timestamp: <unix seconds>
X-Signature: <signature>The script
const CryptoJS = require('crypto-js');
const keyId = pm.environment.get('apiKeyId');
const secret = pm.environment.get('apiSecret');
const timestamp = Math.floor(Date.now() / 1000).toString();
const method = pm.request.method;
const pathWithQuery = pm.request.url.getPathWithQuery();
const body = pm.request.body.raw || '';
const bodyHash = CryptoJS.SHA256(body).toString(CryptoJS.enc.Hex);
const stringToSign = [method, pathWithQuery, timestamp, bodyHash].join('\n');
const signature = CryptoJS.HmacSHA256(stringToSign, secret).toString(CryptoJS.enc.Base64);
pm.request.headers.set('X-Api-Key', keyId);
pm.request.headers.set('X-Timestamp', timestamp);
pm.request.headers.set('X-Signature', signature);Paste it into the Scripts tab of the collection, under Pre-request. Collection and folder scripts run before the request's own script, for every request inside, so every request gets signed.
pm.request.body.raw returns the body with {{variables}} already filled in, which is what you want: the signature must cover the bytes that are sent, not the template.
Keep the secret out of the collection
The script reads apiSecret from the environment. Make it a secret environment variable (encrypted on the server, masked in the app and in reports), or keep it in a local .env file that you load in the app and pass to the CLI with --env-file. Either way, the collection itself contains only the variable name. See keeping API keys out of your collections.
In CI:
requestarium run-collection "Exchange API" --env Sandbox --env-var apiSecret=EXCHANGE_API_SECRETVariations you'll meet
- Hex instead of Base64:
.toString(CryptoJS.enc.Hex). - Milliseconds:
Date.now().toString(). - A nonce: add
require('uuid').v4()to the string and to a header, for APIs that reject replays. - Sorted query parameters: some schemes sign the query sorted by key. Build it from
pm.request.url.getQueryString(), split on&, sort, and join. - Body hash of an empty body: some APIs want the hash of an empty string, others want the line left empty. Check with a
GET. - HMAC-SHA512:
CryptoJS.HmacSHA512.
For AWS, don't write this by hand: pick AWS Signature as the request's auth type, which implements SigV4. See calling IAM-protected APIs with SigV4.
Debugging "invalid signature"
Signature errors say nothing about what's wrong, by design. Log the pieces and compare them with the API's example:
console.log('string to sign:', JSON.stringify(stringToSign));
console.log('body hash:', bodyHash);JSON.stringify shows the newlines as \n, which makes a missing or extra one visible. The output appears in the diagnostics drawer in the app, and in the CLI with --verbose.
The usual causes:
- The body changed after signing: a JSON body reformatted by a tool, or a trailing newline. Sign exactly
pm.request.body.raw. - Path encoding:
/search?q=a bvs/search?q=a%20b. Use the same encoding the server sees. - Clock skew: the server allows a few minutes. A container with the wrong time fails every request.
- Header names: the API wants
X-Signature, you sentX-Sig.
Test the server side too
If it's your API that checks signatures, add negative cases: an old timestamp, a body changed after signing (sign, then set pm.request.body.raw again), and a wrong secret. Each must be 401, and the old-timestamp case should say "expired" rather than "invalid", so client developers know to check their clock.