javascriptnode.jsazureazure-iot-hubazure-iot-sdk

Azure IoT Hub device registration via POSTMAN results in Unauthorized


I want to create a sas token for registration of device in Azure IoT hub,using postman.The sas token will be created with pre-requested script.

    var resourceUri = "scopeId/registrations/deviceId" // The resource uri
    var deviceId = "deviceId";
    
    resourceUri = encodeURIComponent(resourceUri.toLowerCase()); // Encode the url
    
    var expires = Math.ceil((Date.now() / 1000) + 10 * 60); // Expire the token 60 minutes from now
    
    var toSign = resourceUri + "\n" + expires; // this is the string format to gen signature from
    
 var crypted = CryptoJS.HmacSHA256(deviceId, CryptoJS.enc.Base64.parse("symmetrickKeyOfEnrollmentGroup"));

var signature = CryptoJS.HmacSHA256(toSign, crypted); // 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=" + expires +"&skn=registration";

console.log(iotHubSasToken);
postman.setGlobalVariable("token", iotHubSasToken);

This is what i created, but i receive Unauthorized.Some ideas where i am wrong, i think i somewhere in the signature, because the "sr" and "se" are okay

Output of the code above which throws Unauthorized:

SharedAccessSignature sr=0ne002ee24e%2Fregistrations%2Fcxdlx3f3zv9xx3f3zq&sig=Ukz%2FPyyLaweLYmFq4gHUP%2BhiO7X%2FyQAE9noAaw4nuLU%3D&se=1659940252&skn=registration

References:

About SAS: https://learn.microsoft.com/en-us/azure/iot-dps/how-to-control-access

About the REST API: https://learn.microsoft.com/en-us/rest/api/iot-dps/device/runtime-registration/register-device#provisioningserviceerrordetails

About DPS sas token: https://learn.microsoft.com/en-us/azure/iot-dps/how-to-control-access

Error:

enter image description here


Solution

  • The issue was in the signature.

     var crypted = CryptoJS.HmacSHA256(deviceId, CryptoJS.enc.Base64.parse("symmetrickKeyOfEnrollmentGroup"));
    
    var signature = CryptoJS.HmacSHA256(toSign, crypted); // The signature generated from the decodedKey
    var encodedUri = encodeURIComponent(CryptoJS.enc.Base64.stringify(signature)); // The url encoded version of the Base64 signature
    

    This is the right way of creating it.