Azure / azure-powershell

Microsoft Azure PowerShell
Other
4.26k stars 3.86k forks source link

Request access token in scope of ClientId from ManagedIdentityCredential failed #24409

Open Cloud-Architekt opened 8 months ago

Cloud-Architekt commented 8 months ago

Description

Request of access token in scope of the (User-Assigned) Managed Identity Client ID is not working anymore. This scope is required to sign-in as federated identity credentials in AWS by using a Managed Identity. The issue is independent from the Azure Resource type (affects Automation Accounts but also Virtual Machines).

The issue seems to exist since module version 2.15.1 of Az.Accounts.

Used cmdlets: Connect-AzAccount -identity -AccountId Get-AzAccessToken -resource

Error message: Get-AzAccessToken: ManagedIdentityCredential authentication failed: API does not accept client id as a user-provided scope. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot

Current workaround: Request access token from IMDS by using Invoke-WebRequest: $response = Invoke-WebRequest -Uri 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&client_id=<ClientId>&resource=<ClientId>' -Method GET -Headers @{Metadata="true"} $content = $response.Content | ConvertFrom-Json $ArmToken = $content.access_token

Issue script & Debug output

DEBUG: 8:06:21 AM - GetAzureRmAccessTokenCommand begin processing with ParameterSet 'ResourceUrl'.
DEBUG: 8:06:21 AM - using account id '<ClientId>'...
DEBUG: 8:06:21 AM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 8:06:21 AM - [ManagedServiceIdentityAuthenticator] Calling ManagedIdentityCredential.GetTokenAsync - TenantId:'<TenantId>', Scopes:'<ClientId>', UserId:'<ClientId>'
DEBUG: ManagedIdentityCredential.GetToken invoked. Scopes: [ <ClientId> ] ParentRequestId:
DEBUG: False MSAL 4.56.0.0 MSAL.CoreCLR .NET 8.0.1 Microsoft Windows 10.0.22631 [2024-03-19 07:06:21Z - e399a766-3d18-4346-aafa-9a3d5359910c] MSAL MSAL.CoreCLR with assembly version '4.56.0.0'. CorrelationId(e399a766-3d18-4346-aafa-9a3d5359910c)
DEBUG: ManagedIdentityCredential.GetToken was unable to retrieve an access token. Scopes: [ <ClientId> ] ParentRequestId:  Exception: Azure.Identity.AuthenticationFailedException (0x80131500): ManagedIdentityCredential authentication failed: API does not accept client id as a user-provided scope
See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot
 ---> System.ArgumentException (0x80070057): API does not accept client id as a user-provided scope
DEBUG: 8:06:21 AM - [ConfigManager] Got nothing from [DisableErrorRecordsPersistence], Module = [], Cmdlet = []. Returning default value [False].
DEBUG: 8:06:21 AM - [ConfigManager] Got nothing from [EnableDataCollection], Module = [], Cmdlet = []. Returning default value [True].
Get-AzAccessToken: ManagedIdentityCredential authentication failed: API does not accept client id as a user-provided scope
See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot
DEBUG: 8:06:21 AM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 8:06:21 AM - [ConfigManager] Got nothing from [DisplayRegionIdentified], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 8:06:21 AM - [ConfigManager] Got nothing from [CheckForUpgrade], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: AzureQoSEvent:  Module: Az.Accounts:2.16.0; CommandName: Get-AzAccessToken; PSVersion: 7.4.1; IsSuccess: False; Duration: 00:00:00.0646003; Exception: ManagedIdentityCredential authentication failed: API does not accept client id as a user-provided scope
See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot;
DEBUG: 8:06:21 AM - GetAzureRmAccessTokenCommand end processing.

Environment data

Name                           Value
----                           -----
PSVersion                      7.4.1
PSEdition                      Core
GitCommitId                    7.4.1
OS                             Microsoft Windows 10.0.22631
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Module versions

ModuleType Version    PreRelease Name
---------- -------    ---------- ----
Script     2.16.0                Az.Accounts

Error output

DEBUG: 8:17:16 AM - ResolveError begin processing with ParameterSet 'AnyErrorParameterSet'.
DEBUG: 8:17:16 AM - using account id '<ClientId>'...
DEBUG: 8:17:16 AM - [ConfigManager] Got nothing from [DisplayBreakingChangeWarning], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 8:17:16 AM - [ConfigManager] Got nothing from [DisplaySecretsWarning], Module = [], Cmdlet = []. Returning default value [False].

   HistoryId: 3

Message        : ManagedIdentityCredential authentication failed: API does not accept client id as a user-provided
                 scope
                 See the troubleshooting guide for more information.
                 https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot
StackTrace     :    at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String
                 additionalMessage, Boolean isCredentialUnavailable)
                    at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext
                 requestContext, CancellationToken cancellationToken)
                    at Azure.Identity.ManagedIdentityCredential.GetTokenAsync(TokenRequestContext requestContext,
                 CancellationToken cancellationToken)
                    at Microsoft.Azure.PowerShell.Authenticators.MsalAccessTokenAcquirer.GetAccessTokenAsync(String
                 callerClassName, String parametersLog, TokenCredential tokenCredential, TokenRequestContext
                 requestContext, CancellationToken cancellationToken, String tenantId, String userId, String
                 homeAccountId)
                    at Microsoft.Azure.Commands.Common.Authentication.Factories.AuthenticationFactory.Authenticate(IAzu
                 reAccount account, IAzureEnvironment environment, String tenant, SecureString password, String
                 promptBehavior, Action`1 promptAction, IAzureTokenCache tokenCache, String resourceId)
                    at Microsoft.Azure.Commands.Profile.GetAzureRmAccessTokenCommand.ExecuteCmdlet()
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__3`1.<ExecuteSynchronously
                 OrAsJob>b__3_0(T c)
                    at
                 Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T
                 cmdlet, Action`1 executor)
                    at
                 Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T
                 cmdlet)
                    at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
Exception      : Azure.Identity.AuthenticationFailedException
InvocationInfo : {Get-AzAccessToken}
Line           : get-azaccessToken -resource "<ClientId>"
Position       : At line:1 char:1
                 + get-azaccessToken -resource "<ClientId>"
                 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistoryId      : 3

DEBUG: 8:17:17 AM - [ConfigManager] Got nothing from [DisplaySecretsWarning], Module = [], Cmdlet = []. Returning default value [False].
Message        : API does not accept client id as a user-provided scope
StackTrace     :    at Microsoft.Identity.Client.Internal.Requests.RequestBase.ValidateScopeInput(ISet`1
                 scopesToValidate)
                    at Microsoft.Identity.Client.Internal.Requests.RequestBase..ctor(IServiceBundle serviceBundle,
                 AuthenticationRequestParameters authenticationRequestParameters, IAcquireTokenParameters
                 acquireTokenParameters)
                    at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest..ctor(IServiceBundle
                 serviceBundle, AuthenticationRequestParameters authenticationRequestParameters,
                 AcquireTokenForClientParameters clientParameters)
                    at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTok
                 enCommonParameters commonParameters, AcquireTokenForClientParameters clientParameters,
                 CancellationToken cancellationToken)
                    at Azure.Identity.AbstractAcquireTokenParameterBuilderExtensions.ExecuteAsync[T](AbstractAcquireTok
                 enParameterBuilder`1 builder, Boolean async, CancellationToken cancellationToken)
                    at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientCoreAsync(String[] scopes, String
                 tenantId, Boolean enableCae, Boolean async, CancellationToken cancellationToken)
                    at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientAsync(String[] scopes, String
                 tenantId, Boolean enableCae, Boolean async, CancellationToken cancellationToken)
                    at Azure.Identity.ManagedIdentityClient.AuthenticateAsync(Boolean async, TokenRequestContext
                 context, CancellationToken cancellationToken)
                    at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext
                 requestContext, CancellationToken cancellationToken)
Exception      : System.ArgumentException
InvocationInfo : {Get-AzAccessToken}
Line           : get-azaccessToken -resource "<ClientId>"
Position       : At line:1 char:1
                 + get-azaccessToken -resource "<ClientId>"
                 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistoryId      : 3

DEBUG: 8:17:17 AM - [ConfigManager] Got nothing from [DisplayRegionIdentified], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 8:17:17 AM - [ConfigManager] Got nothing from [CheckForUpgrade], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: AzureQoSEvent:  Module: Az.Accounts:2.16.0; CommandName: Resolve-AzError; PSVersion: 7.4.1; IsSuccess: True; Duration: 00:00:00.3137979
DEBUG: 8:17:17 AM - [ConfigManager] Got nothing from [EnableDataCollection], Module = [], Cmdlet = []. Returning default value [True].
DEBUG: 8:17:17 AM - ResolveError end processing.
f-bader commented 7 months ago

This issue also is present when using Azure Automation. Workaround by @Cloud-Architekt works there as well but should be fixed in the codebase

$Uri = "$($env:IDENTITY_ENDPOINT)?api-version=2018-02-01&client_id=$ClientId&resource=$ClientId"
$AzToken = Invoke-WebRequest -Uri $Uri -Method GET -Headers @{ Metadata = "true" } | Select-Object -ExpandProperty Content | ConvertFrom-Json | Select-Object -ExpandProperty access_token
isra-fel commented 7 months ago

@msJinLei could you help look into this? Thanks.

Cloud-Architekt commented 7 months ago

@isra-fel , @msJinLei: Are there any updates on this issue?

msJinLei commented 1 week ago

@Cloud-Architekt You don't need to specify -Resource when you run Get-AzAccessToken except you want to get a data plane token.