title: Generate SaS Token using Python
body: <p>So I took directly from Azure (<a href="https://docs.microsoft.com/pt-br/azure/iot-hub/iot-hub-devguide-security" rel="nofollow noreferrer">https://docs.microsoft.com/pt-br/azure/iot-hub/iot-hub-devguide-security</a>) a Python code to generate the SaS Token. I made the necessary adaptations for my application, but when I use the generated token to send data via POST it returns the following message:</p>
  <p>&quot;Message&quot;:&quot;ErrorCode:IotHubUnauthorizedAccess;Unauthorized&quot;,&quot;ExceptionMessage&quot;:&quot;Tracking ID:c8b0d18b771e465081aa9324293adf73-G:1-TimeStamp:09/08/2020 19:53:52&quot;</p>
  <p>I know how to generate the token using Azure tools in VS Code, but I would like this generation to be incorporated in the code. Below is the code I am using. (Of course, replacing Device ID, Iot Hub Name and the key with those available on the microsoft portal.)</p>
  <pre><code>from base64 import b64encode, b64decode
  from hashlib import sha256
  from time import time
  from urllib import parse
  from hmac import HMAC
  
  
  def generate_sas_token(uri, key, policy_name, expiry=3600):
      ttl = time() + expiry
      sign_key = &quot;%s\n%d&quot; % ((parse.quote_plus(uri)), int(ttl))
      #print (sign_key)
      signature = b64encode(HMAC(b64decode(key), sign_key.encode('utf-8'), sha256).digest())
  
      rawtoken = {
          'sr' :  uri,
          'sig': signature,
          #'se' : str(int(ttl))
      }
  
      if policy_name is not None:
          rawtoken['skn'] = policy_name
  
      rawtoken['se'] = str(int(ttl))
  
      return 'SharedAccessSignature ' + parse.urlencode(rawtoken)
  
  
  resource_uri = IoTHubName + &quot;.azure-devices.net&quot; + &quot;/&quot; + &quot;devices&quot; + &quot;/&quot; + deviceID
  policy_name = &quot;iothubowner&quot;
  
  uri = resource_uri
  key = &quot;primary key=&quot;
  expiry = 3600
  policy= &quot;iothubowner&quot;
  
  print (generate_sas_token(uri, key, policy, expiry))
  </code></pre>