Skip to content

Instantly share code, notes, and snippets.

@lihan
Last active July 13, 2021 13:53
Show Gist options
  • Save lihan/c0d7eeef9a0b375a8f1dd6365f45cb20 to your computer and use it in GitHub Desktop.
Save lihan/c0d7eeef9a0b375a8f1dd6365f45cb20 to your computer and use it in GitHub Desktop.
Postman Pre-request script to add signatures to work with django-rest-framework-httpsignature
/**
* How to use
*
* 1. Place below script in "Pre-request Script" tab in Postman, change "apiKey" and "apiSecret" variable.
* 2. In the "Headers" tab, reference the value as "{{authorisation}}" as per your predefined header name,
* typically "authorization"
* 3. Depending on your server side setup, add header "x-api-key" to your KEY.
*
* Tested with Postman Version 6.0.9
*
*/
var apiKey = 'WFTJJLB344ZJGTG2G83B';
var apiSecret = 'iiHNoVhT9r47r93msq5SDgmd0ICIH9mLD4CnfmBM';
var method = request.method;
var hostMatch = /\/\/(\w+:\d{3,4})/.exec(request.url);
var host = hostMatch[1];
var pathMatch = /:\d{3,4}(.+)/.exec(request.url);
var path = pathMatch[1];
var signatureContentString = [
'(request-target): ' + method.toLowerCase() + ' ' + path,
'host: ' + host.toLowerCase(),
'x-api-key: ' + apiKey
].join('\n');
var signatureString = CryptoJS.HmacSHA256(signatureContentString, apiSecret).toString(CryptoJS.enc.Base64);
var authHeader = 'Signature algorithm="hmac-sha256",headers="(request-target) host x-api-key", signature="'
+ signatureString + '"';
pm.globals.set("authorisation", authHeader);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment