在Powershell中使用Query访问Azure Cosmos DB以获取特定文档时进行未经授权的访问 [英] Unauthorized access while accessing Azure Cosmos DB to get specific document using Query in power shell

查看:66
本文介绍了在Powershell中使用Query访问Azure Cosmos DB以获取特定文档时进行未经授权的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考以下链接,我正在尝试修改Github示例以通过以下方式获取特定文档 在正文中提供查询选项.

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

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

Github示例:

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

我修改了如下代码:

 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

错误:

响应状态代码未指示成功:400(错误请求)

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

推荐答案

我相信问题出在您的$itemResourceId变量上.

I believe the issue is with your $itemResourceId variable.

请更改为:

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

您应该不会遇到此401错误.

and you should not get this 401 error.

如果您注意到了,我从中删除了/docs.

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.

更新

请在您的请求标头中添加以下内容:

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
}

这篇关于在Powershell中使用Query访问Azure Cosmos DB以获取特定文档时进行未经授权的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆