![](/img/trans.png)
[英]How to scale up and down Azure Cosmos DB using some scripts like power shell
[英]Unauthorized access while accessing Azure Cosmos DB to get specific document using Query in power shell
參考下面的鏈接,我正在嘗試通過在正文中提供查詢選項來修改 Github 示例以獲取特定文檔。
鏈接: https://docs.microsoft.com/en-us/rest/api/cosmos-db/querying-cosmosdb-resources-using-the-rest-api
我修改了如下代碼:
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(Bad Request)
我相信問題出在您的$itemResourceId
變量上。
請將其更改為:
$itemResourceId = "dbs/"+$databaseId+"/colls/"+$containerId
你不應該得到這個 401 錯誤。
如果您注意到,我從這里刪除了/docs
。
此外,我發現這個有用的鏈接可能會對您有所幫助: https://github.com/Azure/azure-cosmos-dotnet-v2/blob/master/samples/rest-from-.net/Program.cs 。 這將准確告訴您應該使用哪些值來計算常用操作的授權 header。
更新
請將以下內容添加到您的請求標頭中:
"x-ms-documentdb-query-enablecrosspartition" = "True";
這是對我有用的完整代碼:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.