Unauthorized access while accessing Azure Cosmos DB to get specific document using Query in power shell

落爺英雄遲暮 提交于 2020-04-18 06:11:05

问题


With reference to below link, i am trying to modify Github sample to get specific document by providing query option in Body.

Link: https://docs.microsoft.com/en-us/rest/api/cosmos-db/querying-cosmosdb-resources-using-the-rest-api

Github Sample: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/PowerShellRestApi/PowerShellScripts/ReadItem.ps1

I had modified code like below:

 Add-Type -AssemblyName System.Web
 Function Generate-MasterKeyAuthorizationSignature {

[CmdletBinding()]
param (

    [string] $Verb,
    [string] $ResourceId,
    [string] $ResourceType,
    [string] $Date,
    [string] $MasterKey,
    [String] $KeyType,
    [String] $TokenVersion
)

$keyBytes = [System.Convert]::FromBase64String($MasterKey)

$sigCleartext = @($Verb.ToLower() + "`n" + $ResourceType.ToLower() + "`n" + $ResourceId + "`n" + $Date.ToString().ToLower() + "`n" + "" + "`n")
Write-Host "sigCleartext = " $sigCleartext

$bytesSigClear = [Text.Encoding]::UTF8.GetBytes($sigCleartext)

$hmacsha = new-object -TypeName System.Security.Cryptography.HMACSHA256 -ArgumentList (, $keyBytes)

$hash = $hmacsha.ComputeHash($bytesSigClear) 

$signature = [System.Convert]::ToBase64String($hash)

$key = [System.Web.HttpUtility]::UrlEncode('type=' + $KeyType + '&ver=' + $TokenVersion + '&sig=' + $signature)

return $key
 }

 Function Get-Document {
[string] $endpoint = "https://testcosmos.documents.azure.com/"
[string] $MasterKey = "masterkey=="
[string] $databaseId = "testdb"
[string] $containerId = "containercollection1"

$KeyType = "master"
$TokenVersion = "1.0"
$date = Get-Date
$utcDate = $date.ToUniversalTime()
$xDate = $utcDate.ToString('r', [System.Globalization.CultureInfo]::InvariantCulture)
$itemResourceType = "docs"
$itemResourceId = $null
$itemResourceLink = $null
# $itemResourceId = "dbs/" + $databaseId + "/colls/" + $containerId
$itemResourceLink = "dbs/" + $databaseId + "/colls/" + $containerId + "/docs/"
$itemResourceId = "dbs/" + $databaseId + "/colls/" + $containerId

$verbMethod = "POST"
$requestUri = "$endpoint$itemResourceLink"
$authKey = Generate-MasterKeyAuthorizationSignature -Verb $verbMethod -ResourceId $itemResourceId -ResourceType $itemResourceType -Date $xDate -MasterKey $MasterKey -KeyType $KeyType -TokenVersion $TokenVersion
$itemResourceId
$itemResourceLink
$requestUri
$header = @{

    "x-ms-documentdb-isquery" = "True";

    "authorization"           = "$authKey";

    "x-ms-version"            = "2018-12-31";

    "Cache-Control"           = "no-cache";

    "x-ms-date"               = "$xDate";
}

  $queryJson = @"
 { 
"query": "SELECT * FROM TestCollection c WHERE c.userid = 2",     
"parameters": [ ] 
  }
  "@ 
   try {
      $result = Invoke-RestMethod -Uri $requestUri -Headers $header -Method 
  $verbMethod -ContentType "application/query+json" -Body $queryJson - 
   ErrorAction Stop
    Write-Host "Read item response = "$result

}
catch {
    # Dig into the exception to get the Response details.
    # Note that value__ is not a typo.
    Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 
    Write-Host "Exception Message:" $_.Exception.Message
    Write-Host $_.Exception|format-list -force
  }
 }

  Get-Document

Error:

Response status code does not indicate success: 400 (Bad Request)


回答1:


I believe the issue is with your $itemResourceId variable.

Please change it to:

$itemResourceId = "dbs/"+$databaseId+"/colls/"+$containerId

and you should not get this 401 error.

If you notice, I removed /docs from this.

Also, I found this useful link that you may find helpful: https://github.com/Azure/azure-cosmos-dotnet-v2/blob/master/samples/rest-from-.net/Program.cs. This will tell you exactly what the values that should be used to calculate authorization header for commonly used operation.

UPDATE

Please add the following to your request headers:

"x-ms-documentdb-query-enablecrosspartition" = "True";

Here's the complete code that worked for me:

Add-Type -AssemblyName System.Web

Function Generate-MasterKeyAuthorizationSignature{

    [CmdletBinding()]

    param (

        [string] $Verb,
        [string] $ResourceId,
        [string] $ResourceType,
        [string] $Date,
        [string] $MasterKey,
        [String] $KeyType,
        [String] $TokenVersion
    )

    $keyBytes = [System.Convert]::FromBase64String($MasterKey)

    $sigCleartext = @($Verb.ToLower() + "`n" + $ResourceType.ToLower() + "`n" + $ResourceId + "`n" + $Date.ToString().ToLower() + "`n" + "" + "`n")
    Write-Host "sigCleartext = " $sigCleartext

    $bytesSigClear = [Text.Encoding]::UTF8.GetBytes($sigCleartext)

    $hmacsha = new-object -TypeName System.Security.Cryptography.HMACSHA256 -ArgumentList (, $keyBytes)

    $hash = $hmacsha.ComputeHash($bytesSigClear) 

    $signature = [System.Convert]::ToBase64String($hash)

    $key = [System.Web.HttpUtility]::UrlEncode('type='+$KeyType+'&ver='+$TokenVersion+'&sig=' + $signature)

    return $key
}

$endpoint = "https://account-name.documents.azure.com:443/"
$MasterKey = "account-key=="

$KeyType = "master"
$TokenVersion = "1.0"
$date = Get-Date
$utcDate = $date.ToUniversalTime()
$xDate = $utcDate.ToString('r', [System.Globalization.CultureInfo]::InvariantCulture)
$databaseId = "DatabaseId"
$containerId = "ContainerId"

$itemResourceType = "docs"
$itemResourceId = "dbs/"+$databaseId+"/colls/"+$containerId
$itemResourceLink = "dbs/"+$databaseId+"/colls/"+$containerId+"/docs"
$verbMethod = "POST"

$requestUri = "$endpoint$itemResourceLink"

$authKey = Generate-MasterKeyAuthorizationSignature -Verb $verbMethod -ResourceId $itemResourceId -ResourceType $itemResourceType -Date $xDate -MasterKey $MasterKey -KeyType $KeyType -TokenVersion $TokenVersion

$queryJson = "{`"query`": `"SELECT * FROM test c WHERE c.id = 1 `", `"parameters`": []}"

$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-query-enablecrosspartition" = "True";
    }

try {
    $result = Invoke-RestMethod -Uri $requestUri -Headers $header -Method $verbMethod -Body $queryJson -ContentType "application/query+json"
    Write-Host "Read item response = "$result
    return "ReadItemSuccess";
}
catch {
    # Dig into the exception to get the Response details.
    # Note that value__ is not a typo.
    Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 
    Write-Host "Exception Message:" $_.Exception.Message
    echo $_.Exception|format-list -force
}


来源:https://stackoverflow.com/questions/61245438/unauthorized-access-while-accessing-azure-cosmos-db-to-get-specific-document-usi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!