microsoftgraph / msgraph-sdk-powershell

Powershell SDK for Microsoft Graph
https://www.powershellgallery.com/packages/Microsoft.Graph
Other
691 stars 165 forks source link

Connect-MgGraph v2.9.0-v2.11.1 - Cannot find single tenant application when using a Service Principle with Secret via Environment Variables (works in v2.8.0) #2439

Closed secretworkpersona closed 2 weeks ago

secretworkpersona commented 10 months ago

Describe the bug Attempting to authenticate using a Service Principle with Secret via Environment Variables using Microsoft.Graph Module v2.9.0 fails with the error below. This feature works in v2.8.0. _AADSTS700016: Application with identifier 'clientid' was not found in the directory 'Microsoft'.

To Reproduce Steps to reproduce the behavior:

# Microsoft.Graph v2.9.0
Install-Module Microsoft.Graph -RequiredVersion 2.9.0
$Env:AZURE_CLIENT_ID = 'client_id'
$Env:AZURE_TENANT_ID = 'tenant_id'
$Env:AZURE_CLIENT_SECRET = 'client_secret'
Connect-MgGraph -EnvironmentVariable

Connect-MgGraph : ClientSecretCredential authentication failed: AADSTS700016: Application with identifier 'client_id'
was not found in the directory 'Microsoft'. This can happen if the application has not been installed by the administrator of the tenant or
consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.

Expected behavior Successful session to Microsoft Graph the same as in MicrosoftGraph Module v2.8.0.

# Microsoft.Graph v2.8.0
Install-Module Microsoft.Graph -RequiredVersion 2.8.0
$Env:AZURE_CLIENT_ID = 'client_id'
$Env:AZURE_TENANT_ID = 'tenant_id'
$Env:AZURE_CLIENT_SECRET = 'client_secret'
Connect-MgGraph -EnvironmentVariable

Welcome to Microsoft Graph!

Debug Output

Connect-MgGraph -EnvironmentVariable -Debug
DEBUG: EnvironmentCredential.GetToken invoked. Scopes: [ https://graph.microsoft.com/.default ] ParentRequestId:

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): a
DEBUG: ClientSecretCredential.GetToken invoked. Scopes: [ https://graph.microsoft.com/.default ] ParentRequestId:
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:57Z - MSAL_Id] MSAL
MSAL.Desktop with assembly version '4.56.0.0'. CorrelationId(CorrelationId)
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:57Z - MSAL_Id] ===
AcquireTokenForClientParameters ===
SendX5C: False
ForceRefresh: False
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:57Z - MSAL_Id]
=== Request Data ===
Authority Provided? - True
Scopes - https://graph.microsoft.com/.default
Extra Query Params Keys (space separated) -
ApiId - AcquireTokenForClient
IsConfidentialClient - True
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - CorrelationId
UserAssertion set: False
LongRunningOboCacheKey set: False
Region configured:
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:57Z - CorrelationId] ===
Token Acquisition (ClientCredentialRequest) started:
  Scopes: https://graph.microsoft.com/.default
 Authority Host: login.microsoftonline.com
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:57Z - CorrelationId] The
current authority is targeting the /common or /organizations endpoint which is not recommended. See https://aka.ms/msal-net-client-credentials
for more details.
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:57Z - CorrelationId]
[Instance Discovery] Instance discovery is enabled and will be performed
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:57Z - CorrelationId] [Region
discovery] Not using a regional authority.
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:57Z - CorrelationId] Fetching
 instance discovery from the network from host login.microsoftonline.com.
DEBUG: Request [Request_Id] GET
https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=REDACTED
x-client-SKU:REDACTED
x-client-Ver:REDACTED
x-client-CPU:REDACTED
x-client-OS:REDACTED
client-request-id:REDACTED
return-client-request-id:REDACTED
x-app-name:REDACTED
x-app-ver:REDACTED
x-ms-client-request-id:Request_Id
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.10.3 (.NET Framework 4.8.9181.0; Microsoft Windows 10.0.19045 )
client assembly: Azure.Identity
DEBUG: Response [Request_Id] 200 OK (00.4s)
Strict-Transport-Security:REDACTED
X-Content-Type-Options:REDACTED
Access-Control-Allow-Origin:REDACTED
Access-Control-Allow-Methods:REDACTED
client-request-id:REDACTED
x-ms-request-id:x-ms-request-id
x-ms-ests-server:REDACTED
X-XSS-Protection:REDACTED
Cache-Control:max-age=86400, private
Content-Type:application/json; charset=utf-8
P3P:REDACTED
Set-Cookie:REDACTED
Date:Tue, 14 Nov 2023 20:52:57 GMT
Content-Length:950
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:58Z - CorrelationId]
Authority validation enabled? True.
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:58Z - CorrelationId]
Authority validation - is known env? True.
DEBUG: Request [Request_Id] POST https://login.microsoftonline.com/common/oauth2/v2.0/token
x-client-SKU:REDACTED
x-client-Ver:REDACTED
x-client-CPU:REDACTED
x-client-OS:REDACTED
x-client-current-telemetry:REDACTED
x-client-last-telemetry:REDACTED
x-ms-lib-capability:REDACTED
client-request-id:REDACTED
return-client-request-id:REDACTED
x-app-name:REDACTED
x-app-ver:REDACTED
Content-Type:application/x-www-form-urlencoded
x-ms-client-request-id:Request_Id
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.10.3 (.NET Framework 4.8.9181.0; Microsoft Windows 10.0.19045 )
client assembly: Azure.Identity
DEBUG: Error response [Request_Id] 400 Bad Request (00.3s)
Pragma:no-cache
Strict-Transport-Security:REDACTED
X-Content-Type-Options:REDACTED
client-request-id:REDACTED
x-ms-request-id:x-ms-request-id
x-ms-ests-server:REDACTED
x-ms-clitelem:REDACTED
X-XSS-Protection:REDACTED
Cache-Control:no-store, no-cache
Content-Type:application/json; charset=utf-8
Expires:-1
P3P:REDACTED
Set-Cookie:REDACTED
Date:Tue, 14 Nov 2023 20:52:57 GMT
Content-Length:743
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:58Z - CorrelationId] Response
 status code does not indicate success: 400 (BadRequest).
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:58Z - CorrelationId] Request
retry failed.
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:58Z - CorrelationId]
HttpStatusCode: 400: BadRequest
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:58Z - CorrelationId] ===
Token Acquisition (1004) failed.
 Host: login.microsoftonline.com.
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:58Z - CorrelationId]
Exception type: Microsoft.Identity.Client.MsalServiceException
, ErrorCode: unauthorized_client
HTTP StatusCode 400
CorrelationId CorrelationId
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-14 20:52:58Z - CorrelationId]
Exception type: Microsoft.Identity.Client.MsalServiceException
, ErrorCode: unauthorized_client
HTTP StatusCode 400
CorrelationId CorrelationId

   at Microsoft.Identity.Client.OAuth2.OAuth2Client.ThrowServerException(HttpResponse response, RequestContext requestContext)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.<ExecuteRequestAsync>d__12`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.<GetTokenAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.OAuth2.TokenClient.<SendHttpAndClearTelemetryAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Identity.Client.OAuth2.TokenClient.<SendHttpAndClearTelemetryAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.OAuth2.TokenClient.<SendTokenRequestAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.<SendTokenRequestAsync>d__25.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.<GetAccessTokenAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.<ExecuteAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.<RunAsync>d__12.MoveNext()
DEBUG: ClientSecretCredential.GetToken was unable to retrieve an access token. Scopes: [ https://graph.microsoft.com/.default ] ParentRequestId:
 Exception: Azure.Identity.AuthenticationFailedException (0x80131500): ClientSecretCredential authentication failed: AADSTS700016: Application
with identifier 'Application_Id' was not found in the directory 'Microsoft'. This can happen if the application has not
been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the
 wrong tenant. Trace ID: x-ms-request-id Correlation ID: CorrelationId Timestamp: 2023-11-14
20:52:58Z
 ---> Microsoft.Identity.Client.MsalServiceException (0x80131500): AADSTS700016: Application with identifier
'Application_Id' was not found in the directory 'Microsoft'. This can happen if the application has not been installed by
the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.
Trace ID: x-ms-request-id Correlation ID: CorrelationId Timestamp: 2023-11-14 20:52:58Z
DEBUG: EnvironmentCredential.GetToken was unable to retrieve an access token. Scopes: [ https://graph.microsoft.com/.default ] ParentRequestId:
Exception: Azure.Identity.AuthenticationFailedException (0x80131500): ClientSecretCredential authentication failed: AADSTS700016: Application
with identifier 'Application_Id' was not found in the directory 'Microsoft'. This can happen if the application has not
been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the
 wrong tenant. Trace ID: x-ms-request-id Correlation ID: CorrelationId Timestamp: 2023-11-14
20:52:58Z
 ---> Microsoft.Identity.Client.MsalServiceException (0x80131500): AADSTS700016: Application with identifier
'Application_Id' was not found in the directory 'Microsoft'. This can happen if the application has not been installed by
the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.
Trace ID: x-ms-request-id Correlation ID: CorrelationId Timestamp: 2023-11-14 20:52:58Z

Confirm
ClientSecretCredential authentication failed: AADSTS700016: Application with identifier 'Application_Id' was not found in
the directory 'Microsoft'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any
user in the tenant. You may have sent your authentication request to the wrong tenant. Trace ID: x-ms-request-id Correlation
 ID: CorrelationId Timestamp: 2023-11-14 20:52:58Z
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): a
Connect-MgGraph : ClientSecretCredential authentication failed: AADSTS700016: Application with identifier 'Application_Id'
was not found in the directory 'Microsoft'. This can happen if the application has not been installed by the administrator of the tenant or
consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant. Trace ID:
x-ms-request-id Correlation ID: CorrelationId Timestamp: 2023-11-14 20:52:58Z
At line:1 char:1
+ Connect-MgGraph -EnvironmentVariable -Debug
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-MgGraph], AuthenticationFailedException
    + FullyQualifiedErrorId : Microsoft.Graph.PowerShell.Authentication.Cmdlets.ConnectMgGraph

Module Version

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     2.9.0      Microsoft.Graph.Authentication      {Add-MgEnvironment, Connect-MgGraph, Disconnect-MgGraph, Get-MgContext...}

Environment Data

Name                           Value
----                           -----
PSVersion                      5.1.19041.3636
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.3636
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Additional context Thank you!

timayabi2020 commented 10 months ago

@secretworkpersona please update the sdk version to the latest release (2.9.1)

image
secretworkpersona commented 10 months ago

Thank you for the update. I recreated the issue last week in 2.9.1, but didn't post debug output while preparing for weekend changes. I'll do this today.

For anyone using scripts, this issue is caught by the generic authentication failed exception below. I present an interactive login in this catch block so we continue with a different account.

catch [Azure.Identity.AuthenticationFailedException]

secretworkpersona commented 10 months ago

Describe the bug Attempting to authenticate using a Service Principle with Secret via Environment Variables using Microsoft.Graph Module v2.9.0 and v2.9.1 fails with the error below. This feature works in v2.8.0. _AADSTS700016: Application with identifier 'clientid' was not found in the directory 'Microsoft'.

To Reproduce Steps to reproduce the behavior:

# Microsoft.Graph v2.9.1
Install-Module Microsoft.Graph -RequiredVersion 2.9.1
$Env:AZURE_CLIENT_ID = 'client_id'
$Env:AZURE_TENANT_ID = 'tenant_id'
$Env:AZURE_CLIENT_SECRET = 'client_secret'
Connect-MgGraph -EnvironmentVariable

Connect-MgGraph : ClientSecretCredential authentication failed: AADSTS700016: Application with identifier 'REDACTED'
was not found in the directory 'Microsoft'. This can happen if the application has not been installed by the administrator of the tenant or
consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.

Expected behavior Successful session to Microsoft Graph the same as in MicrosoftGraph Module v2.8.0.

# Microsoft.Graph v2.8.0
Install-Module Microsoft.Graph -RequiredVersion 2.8.0
$Env:AZURE_CLIENT_ID = 'client_id'
$Env:AZURE_TENANT_ID = 'tenant_id'
$Env:AZURE_CLIENT_SECRET = 'client_secret'
Connect-MgGraph -EnvironmentVariable

Welcome to Microsoft Graph!

Debug Output

Connect-MgGraph -EnvironmentVariable -Debug
DEBUG: EnvironmentCredential.GetToken invoked. Scopes: [ https://graph.microsoft.com/.default ] ParentRequestId:

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): a
DEBUG: ClientSecretCredential.GetToken invoked. Scopes: [ https://graph.microsoft.com/.default ] ParentRequestId:
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED] MSAL
MSAL.Desktop with assembly version '4.56.0.0'. CorrelationId(REDACTED)
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED] ===
AcquireTokenForClientParameters ===
SendX5C: False
ForceRefresh: False
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED]
=== Request Data ===
Authority Provided? - True
Scopes - https://graph.microsoft.com/.default
Extra Query Params Keys (space separated) -
ApiId - AcquireTokenForClient
IsConfidentialClient - True
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - REDACTED
UserAssertion set: False
LongRunningOboCacheKey set: False
Region configured:
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED] ===
Token Acquisition (ClientCredentialRequest) started:
  Scopes: https://graph.microsoft.com/.default
 Authority Host: login.microsoftonline.com
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED] The
current authority is targeting the /common or /organizations endpoint which is not recommended. See https://aka.ms/msal-net-client-credentials
for more details.
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED]
[Instance Discovery] Instance discovery is enabled and will be performed
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED] [Region
discovery] Not using a regional authority.
DEBUG: Request [REDACTED] POST https://login.microsoftonline.com/common/oauth2/v2.0/token
x-client-SKU:REDACTED
x-client-Ver:REDACTED
x-client-CPU:REDACTED
x-client-OS:REDACTED
x-client-current-telemetry:REDACTED
x-client-last-telemetry:REDACTED
x-ms-lib-capability:REDACTED
client-request-id:REDACTED
return-client-request-id:REDACTED
x-app-name:REDACTED
x-app-ver:REDACTED
Content-Type:application/x-www-form-urlencoded
x-ms-client-request-id:REDACTED
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.10.3 (.NET Framework 4.8.9181.0; Microsoft Windows 10.0.19045 )
client assembly: Azure.Identity
DEBUG: Error response [REDACTED] 400 Bad Request (00.6s)
Pragma:no-cache
Strict-Transport-Security:REDACTED
X-Content-Type-Options:REDACTED
client-request-id:REDACTED
x-ms-request-id:03f98b26-c409-463d-9f00-f5a5c9cae200
x-ms-ests-server:REDACTED
x-ms-clitelem:REDACTED
X-XSS-Protection:REDACTED
Cache-Control:no-store, no-cache
Content-Type:application/json; charset=utf-8
Expires:-1
P3P:REDACTED
Set-Cookie:REDACTED
Date:Mon, 20 Nov 2023 18:23:10 GMT
Content-Length:743
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED] Response
 status code does not indicate success: 400 (BadRequest).
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED] Request
retry failed.
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED]
HttpStatusCode: 400: BadRequest
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED] ===
Token Acquisition (1004) failed.
 Host: login.microsoftonline.com.
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED]
Exception type: Microsoft.Identity.Client.MsalServiceException
, ErrorCode: unauthorized_client
HTTP StatusCode 400
CorrelationId REDACTED
DEBUG: False MSAL 4.56.0.0 MSAL.Desktop 4.8 or later Windows 10 Enterprise [2023-11-20 18:23:11Z - REDACTED]
Exception type: Microsoft.Identity.Client.MsalServiceException
, ErrorCode: unauthorized_client
HTTP StatusCode 400
CorrelationId REDACTED

   at Microsoft.Identity.Client.OAuth2.OAuth2Client.ThrowServerException(HttpResponse response, RequestContext requestContext)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.<ExecuteRequestAsync>d__12`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.<GetTokenAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.OAuth2.TokenClient.<SendHttpAndClearTelemetryAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Identity.Client.OAuth2.TokenClient.<SendHttpAndClearTelemetryAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.OAuth2.TokenClient.<SendTokenRequestAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.<SendTokenRequestAsync>d__25.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.<GetAccessTokenAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.<ExecuteAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.<RunAsync>d__12.MoveNext()
DEBUG: ClientSecretCredential.GetToken was unable to retrieve an access token. Scopes: [ https://graph.microsoft.com/.default ] ParentRequestId:
 Exception: Azure.Identity.AuthenticationFailedException (0x80131500): ClientSecretCredential authentication failed: AADSTS700016: Application
with identifier 'REDACTED' was not found in the directory 'Microsoft'. This can happen if the application has not
been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the
 wrong tenant. Timestamp: 2023-11-20
18:23:10Z
 ---> Microsoft.Identity.Client.MsalServiceException (0x80131500): AADSTS700016: Application with identifier
'REDACTED' was not found in the directory 'Microsoft'. This can happen if the application has not been installed by
the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.
Timestamp: 2023-11-20 18:23:10Z
DEBUG: EnvironmentCredential.GetToken was unable to retrieve an access token. Scopes: [ https://graph.microsoft.com/.default ] ParentRequestId:
Exception: Azure.Identity.AuthenticationFailedException (0x80131500): ClientSecretCredential authentication failed: AADSTS700016: Application
with identifier 'REDACTED' was not found in the directory 'Microsoft'. This can happen if the application has not
been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the
 wrong tenant. Timestamp: 2023-11-20
18:23:10Z
 ---> Microsoft.Identity.Client.MsalServiceException (0x80131500): AADSTS700016: Application with identifier
'REDACTED' was not found in the directory 'Microsoft'. This can happen if the application has not been installed by
the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.
Timestamp: 2023-11-20 18:23:10Z

Confirm
ClientSecretCredential authentication failed: AADSTS700016: Application with identifier 'REDACTED' was not found in
the directory 'Microsoft'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any
user in the tenant. You may have sent your authentication request to the wrong tenant. Timestamp: 2023-11-20 18:23:10Z
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): a
Connect-MgGraph : ClientSecretCredential authentication failed: AADSTS700016: Application with identifier 'REDACTED'
was not found in the directory 'Microsoft'. This can happen if the application has not been installed by the administrator of the tenant or
consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant. Timestamp: 2023-11-20 18:23:10Z
At line:1 char:1
+ Connect-MgGraph -EnvironmentVariable -Debug
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-MgGraph], AuthenticationFailedException
    + FullyQualifiedErrorId : Microsoft.Graph.PowerShell.Authentication.Cmdlets.ConnectMgGraph

Module Version

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     2.9.1      Microsoft.Graph.Authentication      {Add-MgEnvironment, Connect-MgGraph, Disconnect-MgGraph, Get-MgContext...}

Environment Data

Name                           Value
----                           -----
PSVersion                      5.1.19041.3693
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.3693
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Additional context Thank you again!

timayabi2020 commented 10 months ago

@secretworkpersona I am only able to reproduce the issue if I set the wrong client id on $Env:AZURE_CLIENT_ID environment variable. I suspect this might not necessarily be an SDK issue. Also, see these articles which I think are related to this issue. https://learn.microsoft.com/en-us/answers/questions/692461/message-aadsts700016-application-with-identifier-n and https://stackoverflow.com/questions/66107800/how-to-solve-aadsts700016-error-on-login-with-microsoft-account

secretworkpersona commented 10 months ago

This is definitely a puzzler. Even though the same environment variables work in v2.8.0, to your point I'm also trying to determine if it's our environment. I recently reported an issue passing credentials to MSOnline v1.1.183.80 that was fixed in 1.1.183.81 so there was a wider audience. If nobody else has this Graph authentication issue then it's me, or only a few it may also be their environment.

The error mentions using the /common or /organizations endpoint is not recommended, so I created a second app using our organization's guid endpoint but that did not resolve the issue.

I should have mentioned that as part of my troubleshooting I used the same environment variables values and successfully used them using an interactive login.

Does not authenticate due to app not found:

$Env:AZURE_CLIENT_ID = 'CLIENT_ID'
$Env:AZURE_TENANT_ID = 'TENANT_ID'
$Env:AZURE_CLIENT_SECRET = 'CLIENT_SECRET'
Connect-MgGraph -EnvironmentVariable
<error>

Successfully authenticates using the same values as above using Using CLIENT_SECRET as password:

$ClientSecretCredential = Get-Credential -Credential "CLIENT_ID"
Connect-MgGraph -TenantId "TENANT_ID" -ClientSecretCredential $ClientSecretCredential
Welcome to Microsoft Graph!

This makes me think it's not our environment, but something else including the service itself. But I'm still trying to determine if there is any scenario in our environment where the v2.9.1 environment variable authentication succeeds. Today I will attempt to recreate the issue on a production server in our datacenter using an unattended (scheduled) script.

secretworkpersona commented 9 months ago

Can reproduce in v2.10.0. I see Microsoft.Graph.Authentication src did not change between v2.8.0 and v2.9.0, but the failures use MSAL 4.56.0.0 and target the /common or /organizations endpoints. In v2.8.0 MSAL 4.49.1.0 is called and there is no endpoint warning.

EDIT: Are you able to provide your specific app registration values where you are not able to reproduce the issue? I've been testing with different platforms, URIs, and settings, but have not yet found anything that resolves the issue. Thx.

tbisque commented 9 months ago

+1. Also experiencing this issue with the EnvironmentVariable parameter in v2.8.0+. Experiencing with multiple tenants and cloud types (Global & USGov).

secretworkpersona commented 9 months ago

For us the issue occurs when the application's supported account types is "Accounts in this organizational directory only (Single tenant)". If the application is "Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant)" we can successfully connect using environment variables. I created a test application and by changing its supported account types back and forth between single tenant and multitenant, using environment variables alternately succeeds and fails.

sulian commented 9 months ago

Hello

Any news about this issue ? I'm stuck in 2.8.x because I cannot update to v2.11, I use Service Principal every day to connect to Azure tenant.

tehmichael commented 9 months ago

For us the issue occurs when the application's supported account types is "Accounts in this organizational directory only (Single tenant)". If the application is "Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant)" we can successfully connect using environment variables. I created a test application and by changing its supported account types back and forth between single tenant and multitenant, using environment variables alternately succeeds and fails.

I tried the same with ours and couldn't replicate the same behavior, unfortunately. We're also stuck to version 2.8.0 until this is fixed.

bandlor commented 8 months ago

I'm having this issue also ... Trying to connect to Tenant ID (d264b141-baa3-434e-835d-XXXXXXXXXXXX) and Client ID (ce654747-c430-45f3-9b37-XXXXXXXXXXXX) using Connect-Graph -EnvironmentVariable will return the error:

Connect-MgGraph: ClientSecretCredential authentication failed: AADSTS700016: Application with identifier 'ce654747-c430-45f3-9b37-XXXXXXXXXXXX' was not found in the directory 'Microsoft'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant. Trace ID: 48d66bac-d068-4159-ad02-9118b9490400 Correlation ID: f080fdd1-7ac3-4b5d-9958-32a3156b3326 Timestamp: 2024-01-09 08:58:26Z

This happens to me with PowerShell 7.4.0 and Microsoft.Graph 2.10 and 2.11 on both Mac OS and Windows 10.

Connecting with exactly the same values in the following way works (but requires pasting the secret): $ClientSecretCredential = Get-Credential -Credential $env:AZURE_CLIENT_ID Connect-MgGraph -TenantId $env:AZURE_TENANT_ID -ClientSecretCredential $ClientSecretCredential

I can still connect the old fashion way with MSAL.PS, but I understand I loose the refresh token access like this: Import-Module MSAL.PS $MsalToken = Get-MsalToken -TenantId $env:AZURE_TENANT_ID -ClientId $env:AZURE_CLIENT_ID -ClientSecret ($env:AZURE_CLIENT_SECRET | ConvertTo-SecureString -AsPlainText -Force) $SecureToken = $MsalToken.AccessToken | ConvertTo-SecureString -AsPlainText -Force Connect-Graph -AccessToken $SecureToken -NoWelcome -ErrorAction Stop

This does work even with the newer Graph versions for me but requires the use of MSAL.PS module.

tehmichael commented 8 months ago

@timayabi2020, do you know if there has been any progress on this issue? Is there something we can collect on our side to return to the bug report?

Thank you!

tbisque commented 7 months ago

@timayabi2020 any update on this? This issue is still present in v2.14.1.

Was there a change to how these environment variables need to be defined? The learn article still indicates this -EnvironmentVariable parameter is valid.

Are there different environment variables that need to be defined beyond $env:AZURE_CLIENT_ID, $env:AZURE_TENANT_ID, and $env:AZURE_CLIENT_SECRET?

As @tehmichael mentioned, I'm happy to capture additional logs or provide any more details to aid troubleshooting efforts. Rolling all the way back to 2.8 when this -EnvironmentVariable parameter last functioned is less than ideal.

tbisque commented 7 months ago

For those still facing this issue, I believe I found a valid workaround:

$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $env:AZURE_CLIENT_ID, ($env:AZURE_CLIENT_SECRET | ConvertTo-SecureString -AsPlainText -Force)

Connect-MgGraph -ClientSecretCredential $Credential -TenantId $env:AZURE_TENANT_ID

This is a similar approach to the service principal auth approach in the Connect-AzAccount documentation, and sort of adapted from example 8 in the Connect-MgGraph documentation.