Search code examples
azurepowershellazure-cosmosdb

Unauthorized error when doing PATCH operation to CosmosDB Rest API using Powershell


I am doing a PATCH operation to update existing property in a document in my container. It gives me unauthorized error. Here is my code;

$key = "<MASTERKEY>"
$verb = "PATCH"
$resourceType = "docs"
$resourceLink = "dbs/testsnow/colls/test"
$dateTime = [DateTime]::UtcNow.ToString("r")
$keyType = "master"
$tokenVersion = "1.0"


$hmacSha256 = New-Object System.Security.Cryptography.HMACSHA256
$hmacSha256.Key = [System.Convert]::FromBase64String($key)
 
$payLoad = "$($verb.ToLowerInvariant())`n$($resourceType.ToLowerInvariant())`n$resourceLink`n$($dateTime.ToLowerInvariant())`n`n"
$hashPayLoad = $hmacSha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($payLoad))
$signature = [System.Convert]::ToBase64String($hashPayLoad);
# Add-Type -AssemblyName System.Web
$x = [System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$signature")



$header = @{authorization=$x;"x-ms-version"="2018-12-31";"x-ms-date"=$dateTime;"Content-Type"= "application/json_patch+json";"x-ms-documentdb-partitionkey"='["open"]'}



$document = @{
    "operations" = @(@{"op"="Replace";"path"="/state";"value"="testname"})
} | ConvertTo-Json

$queryUri = "https://<URL>/dbs/testsnow/colls/test/docs/<docid>"

$result = Invoke-RestMethod -Method $verb -Uri $queryUri -Headers $header -Body $document

It gives me below error

{
    "code": "Unauthorized",
    "message": "The input authorization token can't serve the request. The wrong key is being used or the expected payload is not built as per the protocol. For more info: https://aka.ms/cosmosdb-tsg-unauthorized. Server used the following payload to sign: 'patch\ndocs\ndbs/testsnow/colls/test/docs/RITM009953466\nfri, 23 jun 2023 16:37:42 gmt\n\n'\r\nActivityId: 089fe7a1-24a5-4ba2-9cc0-8fcf4b3a9186, Microsoft.Azure.Documents.Common/2.14.0"
}

Solution

  • I was able to find the answer. The $resourceLink value should be:

    ""dbs/testsnow/colls/test/docs/<doc_id>""