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/76e577162e85f0110abc2743458d4771 to your computer and use it in GitHub Desktop.
Save jongio/76e577162e85f0110abc2743458d4771 to your computer and use it in GitHub Desktop.
Azure IoT Hub SAS Token JavaScript CryptoJS
// 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"));
@malkrad
Copy link

malkrad commented Nov 5, 2021

Hi @jongio ,
I would like to use your code in my project.
I can't found a license for the Gist, is it OK?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment