【问题标题】:Azure ARM access token wrong audienceAzure ARM 访问令牌错误的受众
【发布时间】:2021-04-26 20:40:14
【问题描述】:

我正在尝试从 Azure ARM 获取有关特定资源的信息。目前,我可以使用以下文章 https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow 从 oAuth2 获取访问令牌,但是当我尝试使用它时,出现以下错误:

调用-RestMethod : {"error":{"code":"InvalidAuthenticationTokenAudience","message":"The 已为错误的受众或资源获取访问令牌 '00000002-0000-0000-c000-000000000000'。它应该与 允许的观众之一 'https://management.core.windows.net/'、'https://management.core.windows.net'、'https://management.azure.com/'、'https://management.azure .com'。"}}

下面是我尝试运行的代码:

param
(
    [Parameter(Mandatory=$true)][System.String] $ResourceId,
    [Parameter(Mandatory=$true)][System.String] $APIVersion
)
function Urls-Authorization
{
    [OutputType([System.Uri])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$false)] [System.Guid] $TenantId
    )
    return [System.Uri]::new("https://login.microsoftonline.com/$($TenantId)/oauth2/token")
}
function Urls-Management
{
    [OutputType([System.Uri])]
    [CmdletBinding()]
    param()
    return [System.Uri]::new("https://management.azure.com")
}
function Urls-Resource
{
    [OutputType([System.Uri])]
    [CmdletBinding()]
    param()
    return [System.Uri]::new((Urls-Management), "$($ResourceId)?api-version=$($APIVersion)")
}
function ConvertFrom-SecureString
{
    [OutputType([System.String])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true)] [SecureString] $SecureString
    )
    return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString))
}
function New-AccessToken
{
    [OutputType([System.String])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true)] [System.Uri] $ResourceUrl,
        [Parameter(Mandatory=$true)] [System.Guid] $TenantId,
        [Parameter(Mandatory=$true)] [System.Guid] $ClientId,
        [Parameter(Mandatory=$true)] [SecureString] $Password,
        [Parameter(Mandatory=$false)] [System.DateTime] $Expires = ($(Get-Date).AddMinutes(60).ToUniversalTime()),
        [Parameter(Mandatory=$false)] [System.DateTime] $NotBefore = ([System.DateTime]::UtcNow)
    )
    #https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
    $AuthorityUrl = Urls-Authorization -TenantId $TenantId
    try
    {
        $RequestBody = [ordered]@{
                                        'grant_type'    = 'client_credentials';
                                        'client_id'     = $ClientId;
                                        'scope   '      = $ResourceUrl;
                                        'client_secret' = "$(ConvertFrom-SecureString -SecureString $Password)";
                                    }
        $Response = Invoke-RestMethod -Uri $AuthorityUrl -Method Post -Body $RequestBody -ErrorAction Stop
    }
    catch
    {
        Write-Log -Type ERROR -Message "Token could not be acquired"
        throw
    }
    return $Response.access_token
}
function Headers
{
    [OutputType([Hashtable])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$false)] [System.String] $ContentType,
        [Parameter(Mandatory=$true)] [System.String] $AccessToken
    )
    $Headers = @{}
    if ($ContentType -ne $null) {$Headers.Add("Content-Type", $ContentType)}
    $Headers.Add("Authorization", "Bearer $($AccessToken)")
    return $Headers
}
Invoke-RestMethod -Method Get -Uri (Urls-Resource) -Headers (Headers -ContentType "application/json" -AccessToken (New-AccessToken -ResourceUrl (Urls-Management) -TenantId $env:AZURE_TENANT_ID -ClientId $env:AZURE_CLIENT_ID -Password (ConvertTo-SecureString -String $env:AZURE_CLIENT_SECRET -AsPlainText -Force))) | ConvertFrom-Json

如前所述,我通过 New-AccessToken 函数获取访问令牌。我什至尝试了以下操作,但我得到了同样的错误:

  1. 将New-AccessToken中的ResourceUrl参数从Urls-Management改为Urls-Resource
  2. 添加 /.default 到 Urls-管理地址
  3. 添加将 Urls-Management 从 https://management.azure.com 更改为 https://management.azure.com/

你知道会发生什么吗?关于我应该如何面对这个错误的任何想法?

【问题讨论】:

    标签: powershell azure-resource-manager


    【解决方案1】:

    我认为这个错误提供了一些很好的见解。我会将New-AccessToken 更改为:

    function New-AccessToken
    {
        [OutputType([System.String])]
        [CmdletBinding()]
        param
        (
            [Parameter(Mandatory=$true)] [System.Uri] $ResourceUrl,
            [Parameter(Mandatory=$true)] [System.Guid] $TenantId,
            [Parameter(Mandatory=$true)] [System.Guid] $ClientId,
            [Parameter(Mandatory=$true)] [SecureString] $Password,
            [Parameter(Mandatory=$false)] [System.DateTime] $Expires = ($(Get-Date).AddMinutes(60).ToUniversalTime()),
            [Parameter(Mandatory=$false)] [System.DateTime] $NotBefore = ([System.DateTime]::UtcNow)
        )
        #https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
        $AuthorityUrl = Urls-Authorization -TenantId $TenantId
        try
        {
            $RequestBody = [ordered]@{
                                            'grant_type'    = 'client_credentials';
                                            'client_id'     = $ClientId;
                                            'scope   '      = $ResourceUrl;
                                            'client_secret' = "$(ConvertFrom-SecureString -SecureString $Password)";
                                            'resource'      = 'https://management.azure.com/';
                                        }
            $Response = Invoke-RestMethod -Uri $AuthorityUrl -Method Post -Body $RequestBody -ErrorAction Stop
        }
        catch
        {
            Write-Log -Type ERROR -Message "Token could not be acquired"
            throw
        }
        return $Response.access_token
    }
    

    基本上,在$RequestBody 中添加'resource' = 'https://management.azure.com/';。我在这个 repository 中有几个 Azure Rest 调用,但它很正常(尽管这不应该成为问题)。

    此外,您是否考虑过使用Az 模块?它在后台实现所有其余逻辑,并提供与 Azure 资源通信的即用型 cmdlet。

    【讨论】:

    • 谢谢,它有效。我们不能使用 Az 模块 cmdlet,因为该解决方案将是云托管的,并且 Microsoft 不提供对 Azure 上的 Az 模块的支持,仅适用于 AzureRM,并且某些 AzureRm cmdlet 不提供我们正在寻找的信息
    猜你喜欢
    • 2016-03-26
    • 2019-11-07
    • 2021-06-11
    • 2021-06-01
    • 2023-03-25
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 2022-07-04
    相关资源
    最近更新 更多