Skip to content

Instantly share code, notes, and snippets.

@gabrieljoelc
Last active November 24, 2020 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrieljoelc/eedf956842966c41d47322f5b9e2a121 to your computer and use it in GitHub Desktop.
Save gabrieljoelc/eedf956842966c41d47322f5b9e2a121 to your computer and use it in GitHub Desktop.
Pre-request Postman script for sending Azure Service Bus REST requests using a SAS key
GistID: eedf956842966c41d47322f5b9e2a121
// Pre-request Postman script for sending Azure Service Bus REST requests using a SAS key
// https://docs.microsoft.com/en-us/rest/api/eventhub/Generate-SAS-token?redirectedfrom=MSDN#nodejs
// also https://gist.github.com/DinoChiesa/75796b27828cf8e15c91
const sasKey = postman.getEnvironmentVariable("SASKey");
const sasKeyName = postman.getEnvironmentVariable("SASKeyName");
const sbSubDomain = postman.getEnvironmentVariable("REST_SUBDOMAIN");
const topic = postman.getEnvironmentVariable("SB_TOPIC") || 'default-topic-name';
const subscription = postman.getEnvironmentVariable("SB_SUBSCRIPTION") || 'default-sub.default-topic-name';
const uri = `https://${sbSubDomain}.servicebus.windows.net/${topic}/subscriptions/${subscription}.${topic}/messages/head`;
function createSharedAccessToken(uri, saName, saKey) {
if (!uri || !saName || !saKey) {
throw "Missing required parameter";
}
var encoded = encodeURIComponent(uri);
var now = new Date();
var week = 60*60*24*7;
var ttl = Math.round(now.getTime() / 1000) + week;
var signature = encoded + '\n' + ttl;
// hack to make signature utf8 encoded
var signatureUTF8 = JSON.parse(JSON.stringify(signature));
var hash = CryptoJS.HmacSHA256(signatureUTF8, sasKey);
var base64HashValue = CryptoJS.enc.Base64.stringify(hash);
return 'SharedAccessSignature sr=' + encoded + '&sig=' +
encodeURIComponent(base64HashValue) + '&se=' + ttl + '&skn=' + saName;
}
const token = createSharedAccessToken(uri, sasKeyName, sasKey);
postman.setEnvironmentVariable("SASToken", token);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment