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

标签 azure powershell azure-active-directory azure-cosmosdb azure-cosmosdb-sqlapi

我正在尝试使用 REST API 查询 cosmos 数据库集合。我想要使​​用的身份验证方法是 AAD,我无法使用主 key 身份验证,因为我们已将 cosmos db 身份验证限制为只能使用 AAD 身份验证。

我已将角色分配添加到我所属的组中。

下面是我尝试过的脚本

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

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

最佳答案

终于成功了。为了获取 token ,我使用了带有 ResourceUrl 参数的 Get-AzAccessToken 命令。ResourceUrl 的值是 cosmod db 端点。进行此更改后,我的脚本开始工作。

这是完整的脚本


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
}

关于azure - 如何使用 AAD 身份验证在 powershell 中调用 Azure CosmosDB REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75018333/

相关文章:

azure - 如何创建 Azure 服务主体帐户以进行只读 Azure 访问

azure - 无法加载文件或程序集 'Microsoft.Owin.Security.Cookies' 或其依赖项之一。

azure - 如何终止特定的 Azure 辅助角色实例

powershell - 为什么 PowerShell 返回一个新行?

python - 在 Web 应用中使用 SAML 实现 Azure AD 身份验证

azure-active-directory - 自定义属性未显示在Azure AD B2C的用户配置文件中

sql - 如何将数据从一个 Azure 数据库表复制到另一个 Azure 数据库表并转换数据类型?

azure - Azure VM 的多个公共(public) IP

powershell - 从 Confluence 页面获取限制

powershell - 防止胁迫