python - 如何在 python 中为 cosmos db 生成其余授权 token ?

标签 python rest azure-cosmosdb

我在为简单的获取数据库请求生成 cosmos db 的授权 token 时遇到问题。这是我的 Python 代码:

import requests
import hmac
import hashlib
import base64
from datetime import datetime

key = 'AG . . .EZPcZBKz7gvrKiXKsuaPA=='
now = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:00 GMT')
payload = ('get\ndbs\n\n' + now + '\n\n').lower()
signature = base64.b64encode(hmac.new(key, msg = payload, digestmod = hashlib.sha256).digest()).decode()

url = 'https://myacct.documents.azure.com/dbs'
headers = {
    'Authorization': "type=master&ver=1.0&sig=" + signature,
    "x-ms-date": now,
    "x-ms-version": "2017-02-22"
}

res = requests.get(url, headers = headers)
print res.content

产生此错误的原因:

{"code":"Unauthorized","message":"The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'get\ndbs\n\nsun, 08 apr 2018 02:39:00 gmt\n\n'\r\nActivityId: 5abe59d8-f44e-42c1-9380-5cf4e63425ec, Microsoft.Azure.Documents.Common/1.21.0.0"}

最佳答案

格雷格。根据我的观察,您的代码遗漏了 url encode。您可以找到示例代码 here .

请引用我的代码,我的代码对你的代码做了一些微调。

import requests
import hmac
import hashlib
import base64
from datetime import datetime
import urllib

key = '***'
now = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:00 GMT')
print now
payload = ('get\ndbs\n\n' + now + '\n\n').lower()

payload = bytes(payload).encode('utf-8')
key = base64.b64decode(key.encode('utf-8'))

signature = base64.b64encode(hmac.new(key, msg = payload, digestmod = hashlib.sha256).digest()).decode()
print signature

authStr = urllib.quote('type=master&ver=1.0&sig={}'.format(signature))
print authStr

headers = {
    'Authorization': authStr,
    "x-ms-date": now,
    "x-ms-version": "2017-02-22"
}
url = 'https://***.documents.azure.com/dbs'
res = requests.get(url, headers = headers)
print res.content

执行结果:

enter image description here

希望对你有帮助。

关于python - 如何在 python 中为 cosmos db 生成其余授权 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49713990/

相关文章:

python - 根据分组列向包含特定列比例的 Pandas 数据框添加一列

azure-cosmosdb - Azure Cosmos DB CONTAINS 的语法

java.io.FileNotFoundException :/tmp/(Too many open files)

azure - 如何将大小超过 2 MB 的数据作为单个条目添加到 cosmos db 中?

azure - Azure 函数是否支持 Cosmos DB 与 Mongo Api 的绑定(bind)?除了使用 MongoClient 之外还有其他解决方法吗

python - 从类变量调用方法/函数

python - 如何删除矩阵单元格与其值相同的邻居

python - 如何从索引 0、1 或 2 开始每三个索引分割一个字符串?

php - 刷新 token 上的 Firebase REST API INVALID_ARGUMENT

api - 在什么情况下代理会删除 HTTP 请求 header ?