Skip to content

Instantly share code, notes, and snippets.

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 jongio/ca167edfff5b2df010e729594852db92 to your computer and use it in GitHub Desktop.
Save jongio/ca167edfff5b2df010e729594852db92 to your computer and use it in GitHub Desktop.
var iotHubName = pm.environment.get("iotHubName");
var iotHubKey = pm.environment.get("iotHubKey");
var iotHubTokenExpiration = pm.environment.get("iotHubTokenExpiration");
var iotHubPolicyName = pm.environment.get("iotHubPolicyName");
pm.globals.clear("iotHubSasToken"); // clear out token on first run.
// See this doc for details: https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security
var resourceUri = encodeURIComponent(iotHubName + '.azure-devices.net'); // The resource uri
var expiry = Math.ceil((Date.now() / 1000) + iotHubTokenExpiration * 60); // Expire the token 60 minutes from now
var uriExpiry = resourceUri + '\n' + expiry; // this is the string format to gen signature from
var decodedKey = CryptoJS.enc.Base64.parse(iotHubKey); // The SHA256 key is the Base64 decoded version of the IoT Hub key
var signature = CryptoJS.HmacSHA256(uriExpiry, decodedKey); // The signature generated from the decodedKey
var encodedUri = encodeURIComponent(CryptoJS.enc.Base64.stringify(signature)); // The url encoded version of the Base64 signature
// Construct authorization string (shared access signature)
var iotHubSasToken = "SharedAccessSignature sr=" + resourceUri + "&sig=" + encodedUri + "&se=" + expiry;
// Add token if one is present
if (iotHubPolicyName) {
iotHubSasToken += "&skn="+ iotHubPolicyName;
}
// Put in variable to be used in other requests.
pm.globals.set("iotHubSasToken", iotHubSasToken);
console.log("Shared Access Signature:" + pm.globals.get("iotHubSasToken"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment