IoT Hub MQTT Paho issues

Nikola Radovanovic 31 Reputation points
2021-03-25T12:59:47.557+00:00

Hi,
I am wondering how to programatically generate SAS token in Python? I tried couple of things from the web, but none worked.

Second thing is: when I try to connect multiple MQTT clients to the same device, I kept getting disconnect as soon as another client is connected. Why is this? I want to try publish/subscribe using MQTT explorer, but same thing happen when tried to use 2 python processes. I did not experience such issues with Erlang broker or Mosquitto.

Thank you in advance

Azure IoT Hub
Azure IoT Hub

An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.

0 comments No comments

2 answers

Sort by: Most helpful
  1. Nikola Radovanovic 31 Reputation points
    2021-03-26T07:07:26.967+00:00

    By examining source code of azure-iot-cli-extension I came up with this:

    def generate_sas_token(uri, key, policy=None, expiry=3600, absolute=False):
        """
        Create a shared access signature token as a string literal.
        Args:
            uri (str): Uri of target resource.
            policy (str): Name of shared access policy.
            key (str): Shared access key.
            expiry (int): Future expiry (in seconds) of the token to be generated.
            absolute (bool): In general the sas token ttl is generated relative to 'now' (UTC) + expiry.
                Set to true to generate a sas token with no relative start.
        Returns:
            result (str): SAS token as string literal.
        """
        encoded_uri = quote_plus(uri)
        ttl = int(expiry) if absolute else int(time() + expiry)
        sign_key = '%s\n%d' % (encoded_uri, ttl)
        signature = b64encode(HMAC(b64decode(key), sign_key.encode('utf-8'), sha256).digest())
    
        result = {
            'sr': uri,
            'sig': signature,
            'se': str(ttl)
        }
    
        if policy:
            result['skn'] = policy
    
        return 'SharedAccessSignature ' + urlencode(result)
    

    Still, I cant connect one publisher and one subscriber at the same time, so major question still remains.

    Was this answer helpful?

    1 person found this answer helpful.
    0 comments No comments

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.

    1 deleted comment

    Comments have been turned off. Learn more

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.