Please provide powershell sample to set the authentication header for cosmos db REST API with AAd Authentication token

Krishnaraj Poojary 1 Reputation point
2023-01-05T12:42:24.477+00:00

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

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
Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,764 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Konstantinos Passadis 19,386 Reputation points MVP
    2023-01-05T12:57:48.677+00:00

    Hello and Welcome to Microsoft QnA!

    Can you try this :

    # Set variables for the Azure Cosmos DB endpoint and resource token  
    $endpoint = "https://your-cosmosdb-account.documents.azure.com"  
    $resourceToken = "type=resource&ver=1.0&sig=your-signature"  
      
    # Set variables for the Azure AD tenant, client ID, and client secret  
    $tenant = "your-tenant-id"  
    $clientId = "your-client-id"  
    $clientSecret = "your-client-secret"  
      
    # Get the Azure AD access token  
    $accessToken = (Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token" -Body "client_id=$clientId&client_secret=$clientSecret&grant_type=client_credentials&scope=https%3A%2F%2Fcognitiveservices.azure.com%2F.default").access_token  
      
    # Set the authentication header for the Cosmos DB REST API  
    $authHeader = @{  
      "Authorization" = "Bearer $accessToken"  
      "x-ms-date" = [System.DateTime]::UtcNow.ToString("r")  
      "x-ms-version" = "2017-02-22"  
      "x-ms-documentdb-is-upsert" = "true"  
      "x-ms-cosmos-region" = "Central US"  
      "x-ms-documentdb-session-token" = $resourceToken  
    }  
      
    # Make a request to the Cosmos DB REST API using the authentication header  
    $response = Invoke-RestMethod -Method Get -Uri "$endpoint/dbs" -Headers $authHeader  
      
    # Output the response from the API  
    $response  
    

    Please mark the answer as Completed and upvote in case this helped!

    Thank you!


  2. Krishnaraj Poojary 1 Reputation point
    2023-01-10T04:06:31.107+00:00

    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
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.