Last active
November 24, 2020 21:47
-
-
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
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
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