在CosmosDB REST API上授权pkrange查询

时间:2017-11-22 15:59:44

标签: powershell azure azure-cosmosdb

对于测试场景,我想对CosmosDB数据库中的每个分区运行一个存储过程,并且我试图使用PowerShell从CosmosDB获取分区范围列表。

我收到401 - 此查询未经授权的响应,但同一集合上的其他查询工作正常 - 例如执行过程有效。

我用来查询范围的代码是:

Add-Type -AssemblyName System.Web 

# Configure as required
$accountName  = ""
$connectionKey = ""
$collectionName = ""
$databaseName = ""

function GetKey([System.String]$Verb = '',[System.String]$ResourceId = '',
                [System.String]$ResourceType = '',[System.String]$Date = '',
                [System.String]$masterKey = '')
{
    $keyBytes = [System.Convert]::FromBase64String($masterKey) 
    $text = @($Verb.ToLowerInvariant() + "`n" + 
        $ResourceType.ToLowerInvariant() + "`n" + $ResourceId + "`n" + 
        $Date.ToLowerInvariant() + "`n" + "" + "`n")
    $body =[Text.Encoding]::UTF8.GetBytes($text)
    $hmacsha = new-object -TypeName System.Security.Cryptography.HMACSHA256 -ArgumentList (,$keyBytes) 
    $hash = $hmacsha.ComputeHash($body)
    $signature = [System.Convert]::ToBase64String($hash)

    [System.Web.HttpUtility]::UrlEncode($('type=master&ver=1.0&sig=' + $signature))
}

function GetUTDate() {
    $date = get-date
    $date = $date.ToUniversalTime();
    return $date.ToString("r", [System.Globalization.CultureInfo]::InvariantCulture);
}       

function BuildHeaders([string]$action = "get",[string]$resType, [string]$resourceId){
    $authz = GetKey -Verb $action -ResourceType $resType -ResourceId $resourceId -Date $apiDate -masterKey $connectionKey
    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $headers.Add("Authorization", $authz)
    $headers.Add("x-ms-version", '2017-02-22')
    $headers.Add("x-ms-date", $apiDate) 
    $headers.Add("Cache-Control", 'no-cache') 
    $headers.Add("Accept", 'application/json')
    $headers.Add("Content-Type", 'application/json')
    $headers
}

function GetPartitionKeys(){
    $pkranges = "dbs/" + $databaseName + "/colls/" + $collectionName + "/pkranges"
    $headers = BuildHeaders -action Get -resType colls -resourceId $pkranges

    $uri = $rootUri + "/" + $pkranges

    write-host "Calling" $uri
    write-host($headers|Out-String)

    $response = Invoke-RestMethod $uri -Method Get -Headers $headers
}

$rootUri = "https://" + $accountName + ".documents.azure.com"
GetPartitionKeys

我认为问题是在构建Auth标头时使用资源类型,但CosmosDB REST文档没有太多关于查询此资源的信息。目前我得到以下输出:

Calling https://my-account-name.documents.azure.com/dbs/my-db-name/colls/my-coll-name/pkranges

Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.

2 个答案:

答案 0 :(得分:0)

在计算授权标头的has时,ResourceType值应为" pkranges"。

ResourceLink将是" dbs / my-db-name / colls / my-coll-name"您请求的网址是:https://my-account-name.documents.azure.com/dbs/my-db-name/colls/my-coll-name/pkranges

答案 1 :(得分:-1)

Paul-存储过程只能针对分区键执行,而不能针对单个分区键范围执行。

相关问题