0
votes

I am trying to create a permission for a user on a specific collection. Ref: https://www.systemcenterautomation.com/2018/06/cosmos-db-rest-api-powershell/ Ref : https://docs.microsoft.com/en-us/rest/api/cosmos-db/create-a-permission

I am able to create the user using the same basic process, but the permissions fail with a

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

I know there is a Powershell module out there, but this is in our pipleline so I can't use an unsigned module.

Any Ideas? Key is copy/pasted, and works with the similar create user. I wonder about the Resource Type....

# add necessary assembly
Add-Type -AssemblyName System.Web

# generate authorization key
Function Generate-MasterKeyAuthorizationSignature
{
[CmdletBinding()]
Param
(
    [Parameter(Mandatory=$true)][String]$verb,
    [Parameter(Mandatory=$true)][String]$resourceLink,
    [Parameter(Mandatory=$true)][String]$resourceType,
    [Parameter(Mandatory=$true)][String]$dateTime,
    [Parameter(Mandatory=$true)][String]$key,
    [Parameter(Mandatory=$true)][String]$keyType,
    [Parameter(Mandatory=$true)][String]$tokenVersion
)

$hmacSha256 = New-Object System.Security.Cryptography.HMACSHA256
$hmacSha256.Key = [System.Convert]::FromBase64String($key)

$payLoad=$($verb.ToLowerInvariant())`n$($resourceType.ToLowerInvariant())`n$resourceLink`n$($dateTime.ToLowerInvariant())`n`n"
$hashPayLoad = 
$hmacSha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($payLoad))
$signature = [System.Convert]::ToBase64String($hashPayLoad);

[System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$signature")
}
function Create-CosmosPermission {
#https://{databaseaccount}.documents.azure.com/dbs/{db-id}/users/{user-name}/permissions
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)][String]$EndPoint,
    [Parameter(Mandatory=$true)][String]$DataBaseId,
    [Parameter(Mandatory=$true)][String]$CollectionId,
    [Parameter(Mandatory=$true)][String]$MasterKey,
    [Parameter(Mandatory=$true)][String]$userId,
    [Parameter(Mandatory=$true)][String]$collectionLink


)

$Verb = "POST"
$ResourceType = "dbs";
$ResourceLink = "dbs/$DatabaseId/users/$userId/permissions"
$permissionName = "Allow{0}Collection" -f $CollectionId

$dateTime = [DateTime]::UtcNow.ToString("r")
$authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb - resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
$header = @{authorization=$authHeader;"x-ms-version"="2017-02-22";"x-ms-date"=$dateTime}
$contentType= "application/json"
$queryUri = "$EndPoint$ResourceLink"
#$queryUri |Out-String
$body =@{
    id = $permissionName
    permssionMode = "All"
    resource = "dbs/$DatabaseId/colls/$collectionId"

}
$JSON = ConvertTo-Json $body
$result = Invoke-RestMethod -Method $Verb -ContentType $contentType -Uri $queryUri -Headers $header -Body $JSON

return $result.statuscode

}
$userId = "testuser"
$dbid ="TestAudit"
$collectionName = "db"
$CosmosDBEndPoint = ""https://mycosmos.documents.azure.com:443/"
$MasterKey = "mycosmoskey"
Create-CosmosPermission -EndPoint $CosmosDBEndPoint -DataBaseId $dbid -CollectionId $collectionName -userId $userId -MasterKey $MasterKey
1
Hi,does my answer helps you?Jay Gong
I will check in the morning (US East). Hope it works !LarryR
Sure, waiting for your reply.Jay Gong
Somehow, the issue was around the json created. Fixed now , Thanks JayLarryR

1 Answers

0
votes

Please refer to my working code as below:

# add necessary assembly
#
Add-Type -AssemblyName System.Web

# generate authorization key
Function Generate-MasterKeyAuthorizationSignature
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String]$verb,
[Parameter(Mandatory=$true)][String]$resourceLink,
[Parameter(Mandatory=$true)][String]$resourceType,
[Parameter(Mandatory=$true)][String]$dateTime,
[Parameter(Mandatory=$true)][String]$key,
[Parameter(Mandatory=$true)][String]$keyType,
[Parameter(Mandatory=$true)][String]$tokenVersion
)

$hmacSha256 = New-Object System.Security.Cryptography.HMACSHA256
$hmacSha256.Key = [System.Convert]::FromBase64String($key)

$payLoad = "$($verb.ToLowerInvariant())`n$($resourceType.ToLowerInvariant())`n$resourceLink`n$($dateTime.ToLowerInvariant())`n`n"
$hashPayLoad = $hmacSha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($payLoad))
$signature = [System.Convert]::ToBase64String($hashPayLoad);

[System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$signature")
}

# query
Function Post-CosmosDb
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String]$EndPoint,
[Parameter(Mandatory=$true)][String]$DataBaseId,
[Parameter(Mandatory=$true)][String]$CollectionId,
[Parameter(Mandatory=$true)][String]$UserId,
[Parameter(Mandatory=$true)][String]$MasterKey,
[Parameter(Mandatory=$true)][String]$JSON
)

$Verb = "POST"

$ResourceType = "permissions";
$ResourceLink = "dbs/$DatabaseId/users/$UserId"

$dateTime = [DateTime]::UtcNow.ToString("r")
$authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb -resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
$header = @{authorization=$authHeader;"x-ms-version"="2017-02-22";"x-ms-date"=$dateTime}
$contentType= "application/json"
$queryUri = "$EndPoint$ResourceLink/permissions"

$result = Invoke-RestMethod -Method $Verb -ContentType $contentType -Uri $queryUri -Headers $header -Body $JSON
return $result.statuscode


}

# fill the target cosmos database endpoint uri, database id, collection id and masterkey
$CosmosDBEndPoint = "https://***.documents.azure.com:443/"
$DatabaseId = "db"
$CollectionId = "coll"
$UserId = "jay"
$MasterKey = "***"

$JSON = @"
{    
    "id" : "pertest",
    "permissionMode" : "All",
    "resource" : "dbs/rMYPAA==/colls/rMYPAJiQ3OI="
 }
"@

# execute
Post-CosmosDb -EndPoint $CosmosDBEndPoint -DataBaseId $DataBaseId -CollectionId $CollectionId -UserId $UserId -MasterKey $MasterKey -JSON $JSON

Hope it helps you.Any concern,just let me know.