简体   繁体   English

如何调用 Azure CosmosDB REST API 在 powershell 使用 AAD 身份验证

[英]How to Invoke Azure CosmosDB REST API In powershell using AAD authentication

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.我正在尝试使用 REST API 查询 cosmos db 集合。我想使用的身份验证方法是 AAD,我不能使用主密钥身份验证,因为我们已将 cosmos db 身份验证限制为仅使用 AAD 身份验证。

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但是我收到如下 401 错误

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

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.为了获取令牌,我使用了带有 ResourceUrl 参数的 Get-AzAccessToken 命令 ResourceUrl 的值是 cosmod db 端点。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM