如何使用 SAS 对服务总线的 Azure REST API 进行身份验证

发布于 2025-01-10 03:10:45 字数 2229 浏览 0 评论 0原文

我正在尝试使用本文档中提供的 REST API 向服务总线队列发送消息: https://learn.microsoft.com/ en-us/rest/api/servicebus/send-message-to-queue

请注意,我无法使用 Azure 库来执行此任务,因为据我所知,没有可用的 Service Now 并且我正在设置上使用 Python 测试触发器来模拟从 Service Now 进行的 REST API 调用。

我对 存储队列有类似的问题 我尝试重用相同的解决方案,但是服务总线会响应“缺少授权标头” 这是我使用标头中的授权的代码:

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)

这里,sig 是我从共享访问策略下的服务总线队列获得的主键

se 是纪元时间 2从现在起的几年(不含毫秒) skn 是策略的名称

我得到的最终响应是

<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'}

如果我在标题中没有身份验证的情况下发布并使用上面突出显示的问题中的解决方案, 顺便说一句,这是 API 结构: f"https://{service_namespace}.servicebus.windows.net/{queue}/messages?sig={sig}&se={se}&skn={skn}" 我收到此错误:

<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'm trying to send a message to the Service Bus queue using the REST API provided in this document:
https://learn.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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷心人i 2025-01-17 03:10:45

您收到此错误的原因是您错误地计算了共享访问签名。您可以了解更多信息 此处

要使用 python 生成 SAS 令牌,请参阅下面的代码,该代码取自 此处

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)
            }

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)
            }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文