我正在尝试使用PowerShell的REST调用在cosmos db中创建UDF。我正在未经授权生成auth标头。我使用以下方法来构建auth头并为UDF创建进行REST调用。
我在构建auth标头时使用资源类型作为udf。
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 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", '2015-12-16')
$headers.Add("x-ms-date", $apiDate)
$headers
}
function CreateUDF([string]$dbname,[string]$collectionName){
$uri = $rootUri + "/" + $dbname + "/colls/" + $collectionName + "/udfs"
$headers = BuildHeaders -action Post -resType udfs -resourceId $dbname
$response = Invoke-RestMethod -Uri $uri -Method POST -Headers $headers -Body $udfCreationInput
$response
Write-Host ("Create Udf Response is " + $Response)
}
在构建auth标头时不确定这里有什么问题。请帮我完成这项工作。
答案 0 :(得分:0)
我使用以下脚本生成用于通过Rest API创建UDF的授权令牌:
$Verb="POST"
$ResourceType="udfs"
$ResourceId="dbs/brucedb/colls/brucecoll"
$Date=[System.DateTime]::UtcNow.ToString("r")
$text = @($Verb.ToLowerInvariant() + "`n" + $ResourceType.ToLowerInvariant() + "`n" + $ResourceId + "`n" + $Date.ToLowerInvariant() + "`n" + "`n")
$masterKey="<your-master-key>"
$keyBytes = [System.Convert]::FromBase64String($masterKey)
$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)
Add-Type -AssemblyName System.Web
$token=[System.Web.HttpUtility]::UrlEncode($('type=master&ver=1.0&sig=' + $signature))
Write-Host ("the token is:" + $token)
<强> TEST:强>
此外,您可以关注Create User Defined Function,Access control in the Azure Cosmos DB SQL API和此github C#Rest sample。