具有邮差输出的DocumentDB REST API始终"未授权"错误

时间:2016-09-29 11:14:19

标签: javascript rest azure azure-cosmosdb

我想从我的DocumentDB数据库中检索数据而不是一个中间件,因为我必须将它实现到我的Ionic App中。

我关注了Microsoft的this文档,甚至使用了本文档中完全相同的代码(使用Browserify)。

为了测试连接我使用Postman,我输入了所有必需的标题。对于primary-key,我使用了DocumentDB中的{ "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: 'post\ndbs\n\nthu, 29 sep 2016 10:46:49 gmt\n\n'\r\nActivityId: f7ce147d-6ff9-4e4f-aaff-39d3769cc399" }

问题是,DocumentDB的响应始终如下:

var Buffer = require('buffer/').Buffer;
var crypto = require("crypto");
var headers = new Array();
headers['x-ms-date'] = "Thu, 29 Sep 2016 17:50:49 GMT";

function getAuthorizationTokenUsingMasterKey(verb, resourceType, resourceId, headers, masterKey) {
  var key = new Buffer(masterKey, "base64");

  var text = (verb || "").toLowerCase() + "\n" +
             (resourceType || "").toLowerCase() + "\n" +
             (resourceId || "") + "\n" +
             (headers["x-ms-date"] || "").toLowerCase() + "\n" +
             "" + "\n";

  var body = new Buffer(text, "utf8");
  var signature = crypto.createHmac("sha256", key).update(body).digest("base64");
  var MasterToken = "master";
  var TokenVersion = "1.0";

  return "type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + signature;
}
console.log(getAuthorizationTokenUsingMasterKey("POST", "docs", "test_collection_1", headers, "CJTR8odBZJklUUixWPZDRdTXqJrfLpfhTLk...wO2oPHgPyjuBkbhrjTlvKhRxsAAeig=="));

我做错了什么?

JS看起来像这样:

POST request to https://example-database.documents.azure.com/dbs

x-ms-documentdb-isquery: True
x-ms-date: Thu, 29 Sep 2016 17:50:49 GMT
authorization: type%3Dmaster%26ver%3D1.0%26sig%3D3240f1fa7a05...cf845c746bcbb5a1
x-ms-version: 2015-12-16
x-ms-query-enable-crosspartition: true
Accept: application/json
Content-Type: application/query+json

Postman中的标题看起来像那样:

{{1}}

3 个答案:

答案 0 :(得分:0)

您可能只想抓取并调整Azure提供的用于DocumentDB的node.js SDK中的代码。这是您想要的文件:https://github.com/Azure/azure-documentdb-node/blob/master/source/lib/auth.js

答案 1 :(得分:0)

在“服务器使用以下有效负载签名:”之后,您应确认“text”变量是否与错误中返回的有效负载完全匹配。看来你在这个有效载荷的“resourceId”部分给出了类似的错误:DocumentDB - DELETE causes 401 error。例如,在您上面发布的示例中,您似乎只使用文档名称而不是完整的资源链接。看看我对这个问题的答案 - 它应该解释正确的方法。

答案 2 :(得分:0)

根据您的错误消息,您的授权签名与您尝试接近的DocumentDB中的资源不匹配。要使用PostMan测试连接,您需要针对Document DB的REST API实现正确的Http请求。

E.G。

您可以尝试通过https://msdn.microsoft.com/en-us/library/azure/mt489065.aspx列出DocumentDB中的数据库。

通过以下方式生成授权标头:

console.log(getAuthorizationTokenUsingMasterKey("GET", "dbs", "", headers, "{your_key}"));

在PostMan中:

GET request to https://example-database.documents.azure.com/dbs
x-ms-date: Thu, 29 Sep 2016 17:50:49 GMT
authorization: type%3Dmaster%26ver%3D1.0%26sig%3D....
x-ms-version: 2015-08-06

关于如何针对DocumentDB Rest API生成授权令牌,您可以参考https://msdn.microsoft.com/library/azure/dn783368.aspx了解详细信息。