gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 05:22:16 26 4
gpt4 key购买 nike

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

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

我对 storage queues 有类似的问题我尝试重用相同的解决方案,但服务总线会响应“缺少授权 header ”这是我在 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)

这里,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'}

我不知道如何继续此操作,任何提示和建议将不胜感激。

最佳答案

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

要使用 python 生成 SAS token ,请参阅下面的代码,该代码摘自 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)
}

关于python - 如何使用 SAS 对服务总线的 Azure REST API 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71249890/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com