Last active
November 5, 2021 08:50
-
-
Save jongio/76e577162e85f0110abc2743458d4771 to your computer and use it in GitHub Desktop.
Azure IoT Hub SAS Token JavaScript CryptoJS
This file contains 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
// See this doc for details: https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security | |
var resourceUri = encodeURIComponent(postman.getGlobalVariable("hubName") + '.azure-devices.net'); // The resource uri | |
var expiry = Math.ceil((Date.now() / 1000) + postman.getGlobalVariable("expiresInMins") * 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(postman.getGlobalVariable("signingKey")); // 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 token = "SharedAccessSignature sr=" + resourceUri + "&sig=" + encodedUri + "&se=" + expiry; | |
// Add token if one is present | |
if (postman.getGlobalVariable("policyName")) { | |
token += "&skn="+ postman.getGlobalVariable("policyName"); | |
} | |
// Put in variable to be used in other requests. | |
postman.setGlobalVariable("token", token); | |
console.log("Shared Access Signature:" + postman.getGlobalVariable("token")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @jongio ,
I would like to use your code in my project.
I can't found a license for the Gist, is it OK?