Home > Net >  How to Invoke Azure CosmosDB REST API In powershell using AAD authentication
How to Invoke Azure CosmosDB REST API In powershell using AAD authentication

Time:01-09

I am trying to query the cosmos db collection using REST API. Authentication method I want use is AAD, I can't use master key authentication because we have restricted cosmos db authentication to only to use the AAD authentication.

I have added Role assignment to the group of which I am part of.

Below is the script which I tried

Param(    
    [string] $AccountName,
    [string] $DatabaseName,
    [string] $ResourceGroupName
)

$azContext = Get-AzContext
$azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azProfile)
$token = $profileClient.AcquireAccessToken($azContext.Subscription.TenantId)



$dateTime = [DateTime]::UtcNow.ToString("r")

$keyType="aad"

$tokenVersion="1.0"

$authHeader=[System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$($token.AccessToken)")
$header = @{authorization=$authHeader;"x-ms-version"="2018-12-31";"x-ms-documentdb-isquery"="True";"x-ms-date"=$dateTime}
$contentType= "application/query json"
$collectionName="CapabilityManagement.Capability"
$restUri="https://$AccountName.documents.azure.com/dbs/$DatabaseName/colls/$collectionName/docs"


    $query=@"
{  
  "query": "SELECT * FROM contacts c WHERE c.id = @id",  
  "parameters": [  
    {  
      "name": "@id",  
      "value": "57128516-26ff-475d-95bc-6d54c4b91b89"  
    }
  ]  
} 
"@

 
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    $result = Invoke-RestMethod -Method Post -ContentType $contentType -Uri $restUri -Headers $header -Body $query

But I am getting 401 error as below

Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.
At C:\Users\Ksp\Documents\test.ps1:49 char:15
  ...   $result = Invoke-RestMethod -Method Post -ContentType $contentType  ...
                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
      FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

CodePudding user response:

Finally got this working. To get the Token I used Get-AzAccessToken command with ResourceUrl parameter The Value for the ResourceUrl is cosmod db endpoint. After this change my script started working.

Here is the complete script


Param(    
    [string] $AccountName,
    [string] $DatabaseName,
    [string] $ResourceGroupName,
    [string] $WorkGroupId

)

$token=Get-AzAccessToken -ResourceUrl "https://$AccountName.documents.azure.com"
$restUri="https://$AccountName.documents.azure.com:443/dbs/$DatabaseName/colls/CapabilityManagement.Capability/docs"

$dateTime = [DateTime]::UtcNow.ToString("r")
$keyType="aad"
$tokenVersion="1.0"
$authHeader=[System.Web.HttpUtility]::UrlEncode("type=$keyType&ver=$tokenVersion&sig=$($token.Token)")
$header = @{"authorization"=$authHeader;"x-ms-version"="2018-12-31";"x-ms-date"=$dateTime;"x-ms-documentdb-isquery"="True";"x-ms-documentdb-query-enablecrosspartition"="True"}
$contentType= "application/query json"

$query=@"
{  
  "query": "SELECT * FROM c WHERE c.workgroupId = @workgroupId",  
  "parameters": [  
    {  
      "name": "@workgroupId",  
      "value": "$WorkGroupId"
    }
  ]  
} 
"@

try {
     [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    $result = Invoke-RestMethod -Method Post  -Uri $restUri -Headers $header -ContentType $contentType -Body $query
} 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 "StatusDescription:" $_.Exception.Response.StatusDescription
     Write-Host $_.Exception
}
  • Related