【发布时间】:2020-07-28 06:09:09
【问题描述】:
我正在尝试访问 azure cosmos db 帐户集合文档以及集合中的每个文档。我参考了下面的链接并更改了所有必要的 cosmos db 值,例如 databaseid、container、itemid 主密钥等,
链接:
但我在 Powershell 中运行时遇到错误。
错误:
StatusCode: 401
Exception Message: The remote server returned an error: (401) Unauthorized.
System.Net.WebException: The remote server returned an error: (401) Unauthorized.
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
注意:当我在邮递员中尝试相同时,我正在获取文档列表,但是当我尝试获取特定文档时。我遇到了错误。
错误:
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:
仅供参考:我是 azure 门户中 Cosmodb 帐户的贡献者角色
参数:
$endpoint = "https://testcosmos.documents.azure.com:443/"
$MasterKey = "<Key from Cosmos db account>"
$KeyType = "master"
$TokenVersion = "1.0"
$date = Get-Date
$utcDate = $date.ToUniversalTime()
$xDate = $utcDate.ToString('r',
[System.Globalization.CultureInfo]::InvariantCulture)
$databaseId = "testdb"
$containerId = "containercollection"
$itemResourceType = "docs"
$ItemId="1"
$itemResourceId = "dbs/"+$databaseId+"/colls/"+$containerId+"/docs/"
$itemResourceLink = "dbs/"+$databaseId+"/colls/"+$containerId+"/docs/"
$verbMethod = "GET"
$header = @{
"authorization" = "$authKey";
"x-ms-version" = "2018-12-31";
"Cache-Control" = "no-cache";
"x-ms-date" = "$xDate"
"Accept" = "application/json";
"User-Agent" = "PowerShell-RestApi-Samples";
"x-ms-documentdb-partitionkey" = '["testPK"]'
}
我曾尝试评论“Accept”、“User-Agent”、Cache-Control 标头选项,但没有成功。 我也尝试只获取没有 itemID 的 /docs 列表,但这也是徒劳的。
$result = Invoke-RestMethod -Uri $requestUri -Headers $header -Method $verbMethod -ContentType "application/json"
Write-Host "Read item response = "$result
更新代码:我终于明白为什么会出现问题了。它既不是身份验证问题也不是资源ID。我在标题中传递分区键,这些分区键不是按照 sample 硬编码的。当我将值传递给分区键时,它没有正确使用,因此导致问题。下面是我的动态代码传递分区键
"x-ms-documentdb-partitionkey" = '["$Partitionkey"]' -- Displaying as
[$Partitionkey] but it must print in headers like ["partitionkeyValue"]
正在尝试如何解决这个问题。非常感谢您的建议。
【问题讨论】:
-
请编辑您的问题并包含您传递给此 PS 函数的参数。
-
您的
$itemResourceId和$itemResourceLink中不是缺少$ItemId吗?他们都应该是"dbs/"+$databaseId+"/colls/"+$containerId+"/docs/"+$ItemId。 -
添加 $itemId 也会产生同样的错误。所以我特意删除了我是否得到了整个文档列表但没有得到
-
我刚刚从github.com/Azure/azure-cosmos-dotnet-v3/blob/master/…(您引用的链接)复制了代码并运行了代码,我能够获取文档详细信息。我只是根据我的帐户设置更改了端点、主密钥、数据库和容器 ID。
-
团队,我更新了我的代码
标签: powershell azure-cosmosdb azure-powershell azure-cosmosdb-sqlapi