Home > Software engineering >  How to authenticate Azure REST APIs to Service Bus with SAS
How to authenticate Azure REST APIs to Service Bus with SAS

Time:02-24

I'm trying to send a message to the Service Bus queue using the REST API provided in this document: https://docs.microsoft.com/en-us/rest/api/servicebus/send-message-to-queue

Do note that I cannot use the Azure Libraries for this task as there are non available that I know of for Service Now and I'm setting up the test trigger in Python to simulate the REST API calls that would be made from Service Now.

I had a similar question with regards to storage queues and I've tried reusing the same solution however the Service Bus would respond with "Missing Authorization Header" This is my code that uses the Authorization in the header:

import requests
api = f"https://{service_namespace}.servicebus.windows.net/{queue}/messages?"
msg = """<QueueMessage>  
<MessageText>Testing 1234</MessageText>  
</QueueMessage>
"""
header = {
    "Authorization": f"SharedAccessSignature sr=https://{service_namespace}.servicebus.windows.net/{queue}&sig={sig}&se={se}&skn={skn}",
    "Content-Type": "application/atom xml;type=entry;charset=utf-8"
}
resp = requests.post(api, data=msg, headers=header)
print(resp)
print(resp.text)
print(resp.headers)

Here, sig is the primary key I got from the Service Bus's Queue under Shared Access Policy

se is the epoch time 2 years from now (w/o mili seconds) skn is the name of the policy

The final response I get is

<Response [401]>

{'Content-Length': '0', 'Server': 'Microsoft-HTTPAPI/2.0', 'Strict-Transport-Security': 'max-age=31536000', 'Date': 'Thu, 24 Feb 2022 09:27:17 GMT'}

If I post without the Auth in the header and use the solution in the highlighted question above, This is the API structure BTW: f"https://{service_namespace}.servicebus.windows.net/{queue}/messages?sig={sig}&se={se}&skn={skn}" I get this error:

<Error><Code>401</Code><Detail>MissingToken: The authorization header was not found. To know more visit https://aka.ms/sbResourceMgrExceptions. . TrackingId:<redacted>, SystemTracker:<redacted>.servicebus.windows.net:<redacted>/messages, Timestamp:2022-02-24T09:31:09</Detail></Error>
{'Transfer-Encoding': 'chunked', 'Content-Type': 'application/xml; charset=utf-8', 'Server': 'Microsoft-HTTPAPI/2.0', 'Strict-Transport-Security': 'max-age=31536000', 'Date': 'Thu, 24 Feb 2022 09:31:09 GMT'}

I am not sure how to proceed with this, any tips and suggestion would be much appreciated.

CodePudding user response:

The reason you are getting this error is because you are computing the shared access signature incorrectly. You can learn more about it here.

To generate SAS token using python, please see the code below which is taken from here:

import time
import urllib
import hmac
import hashlib
import base64

def get_auth_token(sb_name, eh_name, sas_name, sas_value):
    """
    Returns an authorization token dictionary 
    for making calls to Event Hubs REST API.
    """
    uri = urllib.parse.quote_plus("https://{}.servicebus.windows.net/{}" \
                                  .format(sb_name, eh_name))
    sas = sas_value.encode('utf-8')
    expiry = str(int(time.time()   10000))
    string_to_sign = (uri   '\n'   expiry).encode('utf-8')
    signed_hmac_sha256 = hmac.HMAC(sas, string_to_sign, hashlib.sha256)
    signature = urllib.parse.quote(base64.b64encode(signed_hmac_sha256.digest()))
    return  {"sb_name": sb_name,
             "eh_name": eh_name,
             "token":'SharedAccessSignature sr={}&sig={}&se={}&skn={}' \
                     .format(uri, signature, expiry, sas_name)
            }
  • Related