I am trying to access azure cosmos db account collection documents and also each document in collection. I had referred below link and changed all necessary cosmos db values like databaseid,container,itemid master key etc.,
Link:
But i am getting below error while running in Powershell.
Error:
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()
NOTE: When i tried same in postman, i am getting list of documents but when i tried to get specific document . I am getting below error.
Error:
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:
FYI: I am contributor role for Cosmodb account in azure portal
Parameters:
$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"]'
}
I had tried commenting "Accept","User-Agent", Cache-Control header options but in vain. I also tried just getting only list of /docs without itemID but that also went in vain.
$result = Invoke-RestMethod -Uri $requestUri -Headers $header -Method $verbMethod -ContentType "application/json"
Write-Host "Read item response = "$result
Updated Code: I finally able to understand why issue is coming. its neither authentication issue nor resourceID. I am passing partition key in headers which is not hard coded as per sample . When i am passing value to partition key, it was not taking correctly hence causing issue. Below is my dynamic Code passing partition key
"x-ms-documentdb-partitionkey" = '["$Partitionkey"]' -- Displaying as
[$Partitionkey] but it must print in headers like ["partitionkeyValue"]
Am trying how to fix that. Many many thanks for your suggestions.
$ItemId
in your$itemResourceId
and$itemResourceLink
? Both of them should be"dbs/"+$databaseId+"/colls/"+$containerId+"/docs/"+$ItemId
. - Gaurav Mantri