microsoftgraph / msgraph-sdk-powershell

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

Connect-MgGraph Interactive not working if connected at first to Exchange Online PS #2227

Closed cyrkin closed 11 months ago

cyrkin commented 1 year ago

Describe the bug Since I updated my Graph module to V2 I have problems signing-in interactively with Connect-MgGraph if I signed-in at least once with Connect-ExchangeOnline (V3) in the same context. If I sign-in first to Graph, it works. Even afterwards, if I sign-in to Exchange Online it keeps working for Graph. I just have to sign-In to Graph at first everytime I open a new Powershell terminal in VSCode. If I don't, I can't sign-in interactively (but with a certificate it works). Also, the user account for Exchange Online (Exchange Admin) is not the same as for the Graph interactive Sign-In (send email as non-admin user).

PS : I don't know if it's trying to retrieve some existing token instead of opening the window, but my computer's PRT should be the one of my end-user account, the windows profile is synced to this account (hybrid-joined computer).

To Reproduce

  1. Be connected interactively to the ExchangeOnlineManagement Powershell module at least once before launching Connect-MgGraph (Connect-ExchangeOnline), even if disconnected in the meantime
  2. Connect-MgGraph -ClientID "XXX" -TenantId "XXX" (To sign-in interactively on Graph)

Expected behavior A Modern sign-in window pops up.

Debug Output

DEBUG: InteractiveBrowserCredential.Authenticate invoked. Scopes: [ User.Read ] ParentRequestId: 

DEBUG: Executing interactive authentication workflow inline.

DEBUG: InteractiveBrowserCredential.Authenticate was unable to retrieve an access token. Scopes: [ User.Read ] ParentRequestId:  Exception: Azure.Identity.AuthenticationFailedException (0x80131500): 
InteractiveBrowserCredential authentication failed: Method not found: '!0 Microsoft.Identity.Client.AbstractApplicationBuilder`1.WithInstanceDiscovery(Boolean)'.
 ---> System.MissingMethodException (0x80131513): Method not found: '!0 Microsoft.Identity.Client.AbstractApplicationBuilder`1.WithInstanceDiscovery(Boolean)'.

Connect-MgGraph : InteractiveBrowserCredential authentication failed: Method not found: '!0 Microsoft.Identity.Client.AbstractApplicationBuilder`1.WithInstanceDiscovery(Boolean)'.
At line:1 char:15
+ ...             Connect-MgGraph -ClientID $targetAppId  -TenantId "160821 ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Connect-MgGraph], AuthenticationFailedException
    + FullyQualifiedErrorId : Microsoft.Graph.PowerShell.Authentication.Cmdlets.ConnectMgGraph

Module Version

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     2.2.0      Microsoft.Graph.Authentication      {Add-MgEnvironment, Connect-MgGraph, Disconnect-MgGraph, Get-MgContext...}
ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     3.2.0      ExchangeOnlineManagement            {Add-VivaModuleFeaturePolicy, Get-ConnectionInformation, Get-DefaultTenantBriefingConfig, Get-DefaultTenantMyAnalyticsFeatureConfig...}

Environment Data

Name                           Value
----                           -----
PSVersion                      5.1.19041.3031
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.3031
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
cyrkin commented 1 year ago

Today it stopped working even before I connected to Exchange Online.

Steps to reproduce :

  1. Open VS Code
  2. Open Windows Configuration Manager (or maybe any app you would expect to open an interactive Sign-In)
  3. Sign-In (in this app, by requesting the bulk enrollment token (here the app did not open an interactive sign-in, though I was hoping it would, and signed-me in with the wrong account (the end-user one)))
  4. connect-MgGraph fails with the same error

Restart VS Code and it works now.

I have a colleague who has the exact same problem in a similar environment. It's like the modern sign-in, instead of opening the interactive Sign-in window, wants to retrieve and use an existing token for SSO, but it's not the right one...

ThoughtContagion commented 1 year ago

We saw the same behavior with certificate authentication. Connecting to Graph before Exchange seems to have resolved this for us. The error we ran into was Connect-MgGraph : ClientCertificateCredential authentication failed: Could not load type 'Microsoft.Identity.Client.Extensibility.AppTokenProviderParameters' from assembly 'Microsoft.Identity.Client, Version=4.36.1.0, Culture=neutral, PublicKeyToken=0a613f4dd989e8ae'.

peombwa commented 1 year ago

I'm not able to reproduce the error with the provided steps. Both commands work as expected when used together in PowerShell 5.1: image

Please ensure that you are using the latest version of the SDK, and that your environment is configured correctly as stated at https://learn.microsoft.com/powershell/microsoftgraph/installation?view=graph-powershell-1.0#prerequisites.

Cyb3r4rch3r commented 1 year ago

The version you have tested and confirmed working 29 minutes ago, was not available on August 8th.

This response feels a lot like placing the blame on the user that opened this issue - obviously the issue was resolved in one of the multiple updates since the issue was created.

image

Have you tried reproducing this issue with the version that the issue was opened on?

peombwa commented 1 year ago

@Cyb3r4rch3r, the goal is not to blame, but to work with user to help resolve the issue. Please take note of our troubleshooting guide at https://learn.microsoft.com/powershell/microsoftgraph/troubleshooting?view=graph-powershell-1.0 which calls for using the latest version to verify bugs:

The version of the Microsoft.Graph module should be the most recent compared to the latest release in the PowerShell Gallery. If your installed module isn't up to date, update it by running...

Have you tried reproducing this issue with the version that the issue was opened on?

Yes, even with v2.2.0, the error is not thrown: image

Are you able to reproduce the error with v2.2.0? If so, please share the output of:

cyrkin commented 1 year ago

Hello,

Some updates on this topic. First, it does not seem to be the particular Connect-ExchangeOnline CmdLet who triggers the problem. But any/some non-Interactive Azure Sign-in made on the computer (cf. my previous message). I think that, because sometimes I do not have to launch this cmdlet to have the problem, for example :

Particular context : I open my windows Session using an Azure AD Hybrid account, it's my end-User account. But, I also have an Edge profile signed-in with my admin account (which may create a second "work or school account" on the computer, therefore a second PRT maybe ?) to make the Conditional Access work. ,It's this Admin account that I wish to use in my scripts, therefore needing the interactive (and not SSO) sign-In.

Still in 2.2.0 I launched your first command after trigerring the problem, here's the result :

ErrorRecord                 : InteractiveBrowserCredential authentication failed: Method not found: '!0 Microsoft.Identity.Client.AbstractApplicationBuilder`1.WithInstanceDiscovery(Boolean)'.
WasThrownFromThrowStatement : False
Message                     : The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: InteractiveBrowserCredential authentication failed: Method not 
                              found: '!0 Microsoft.Identity.Client.AbstractApplicationBuilder`1.WithInstanceDiscovery(Boolean)'.
Data                        : {System.Management.Automation.Interpreter.InterpretedFrameInfo}
InnerException              :
TargetSite                  : System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject] Invoke(System.Collections.IEnumerable)
StackTrace                  :    at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
                                 at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork(Runspace rs, Boolean performSyncInvoke)
                                 at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, Boolean isSync)
                                 at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
                                 at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
                                 at System.Management.Automation.PowerShell.Invoke[T](IEnumerable input, PSInvocationSettings settings)
                                 at Microsoft.PowerShell.EditorServices.Services.PowerShell.Utility.PowerShellExtensions.InvokeAndClear[TResult](PowerShell pwsh, PSInvocationSettings invocationSettings)
                                 at Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution.SynchronousPowerShellTask`1.ExecuteNormally(CancellationToken cancellationToken)
HelpLink                    :
Source                      : System.Management.Automation
HResult                     : -2146233087

I'm gonna do the same after updating the Graph Module.

cyrkin commented 1 year ago

Updated to 2.6.1 Same problem... Triggered it by declaring the function first (cf. previous message)


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     2.6.1      Microsoft.Graph.Authentication      {Add-MgEnvironment, Connect-MgGraph, Disconnect-MgGraph, Get-MgContext...}
Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {ConvertFrom-SecureString, ConvertTo-SecureString, Get-Acl, Get-AuthenticodeSignature...}
Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
Script     0.2.0      PowerShellEditorServices.Commands   {Clear-Host, ConvertFrom-ScriptExtent, ConvertTo-ScriptExtent, Find-Ast...}
Binary     0.2.0      PowerShellEditorServices.VSCode     {Close-VSCodeHtmlContentView, New-VSCodeHtmlContentView, Set-VSCodeHtmlContentView, Show-VSCodeHtmlContentView...}
Script     2.2.6      PSReadLine                          {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PSReadLineKeyHandler, Set-PSReadLineKeyHandler...}

Coworker in the same context (Hybrid end-user profile + Azure admin account + VSCode) has the exact same problem.

jonade commented 1 year ago

I was able to reproduce this same InteractiveBrowserCredential authentication failed: Method not found: '!0 Microsoft.Identity.Client.AbstractApplicationBuilder1.WithInstanceDiscovery(Boolean)' error message with the 1.1.183.80 version of MSOnline module installed along with 2.6.1 of the Microsoft.Graph.Authentication module. It would only trigger if Connect-MsolService had been run prior to Connect-MgGraph. If skipping connection to MSOL and directly running Connect-MgGraph it would work fine.

So steps to reproduce end up being

  1. Install-Module -Name MSOnline -RequiredVersion 1.1.183.80
  2. Connect-MsolService
  3. Connect-MgGraph

If I downgrade back to previous version of MSOnline this returns back to normal behaviour:

  1. Uninstall-Module -Name MSOnline -RequiredVersion 1.1.183.80
  2. Install-Module -Name MSOnline -RequiredVersion 1.1.183.66
  3. Connect-MsolService
  4. Connect-MgGraph

The question becomes, why should the Graph SDK be affected by other external modules? It should be irrelevant what other modules are installed for correct functioning.

yukieryu commented 1 year ago

I was able to reproduce the same error following the steps by jonade.

Install-Module -Name MSOnline -RequiredVersion 1.1.183.80 Connect-MsolService Connect-MgGraph

moiaune commented 1 year ago

I've experienced the same error the last couple of days when trying to connect to Microsoft Graph from Windows Powershell (Microsoft.Graph.Authentication v2.8.0) using device code authentication. BUT it only happens if I import module ExchangeOnlineManagement or run Connect-ExchangeOnline first.

TylerHagan1980 commented 1 year ago

I was able to reproduce this same InteractiveBrowserCredential authentication failed: Method not found: '!0 Microsoft.Identity.Client.AbstractApplicationBuilder1.WithInstanceDiscovery(Boolean)' error message with the 1.1.183.80 version of MSOnline module installed along with 2.6.1 of the Microsoft.Graph.Authentication module. It would only trigger if Connect-MsolService had been run prior to Connect-MgGraph. If skipping connection to MSOL and directly running Connect-MgGraph it would work fine.

So steps to reproduce end up being

  1. Install-Module -Name MSOnline -RequiredVersion 1.1.183.80
  2. Connect-MsolService
  3. Connect-MgGraph

If I downgrade back to previous version of MSOnline this returns back to normal behaviour:

  1. Uninstall-Module -Name MSOnline -RequiredVersion 1.1.183.80
  2. Install-Module -Name MSOnline -RequiredVersion 1.1.183.66
  3. Connect-MsolService
  4. Connect-MgGraph

The question becomes, why should the Graph SDK be affected by other external modules? It should be irrelevant what other modules are installed for correct functioning.

I was able to resolve, temporarily, the issue by following the above.

carl0ski commented 1 year ago

My understanding it set retention compliance policy can only be managed by this ExchangeOnlineManagement Set-RetentionCompliancePolicy -Identity "Retention" -AddOneDriveLocationException $($validUrls)

I've experienced the same error the last couple of days when trying to connect to Microsoft Graph from Windows Powershell (Microsoft.Graph.Authentication v2.8.0) using device code authentication. BUT it only happens if I import module ExchangeOnlineManagement or run Connect-ExchangeOnline first.

I was also able to reproduce this Load ExchangeOnlineManagement and the same occurs

I get it straight after Connect-IPPSSession also part of the ExchangeOnlineManagement package

and it spends over 1 minute Importing module 'Microsoft.Graph'...

and then finally the loaded module connect mg-graph will fail with variety of token errors

I was required to remove Module "ExchangeOnlineManagement" to restore ability to connect mg-graph

timayabi2020 commented 11 months ago

@carl0ski I haven't been able to reproduce the issue with the latest SDK version. (2.11.1). Please also note that the interactive browser issue was fixed in version 2.9.1

microsoft-github-policy-service[bot] commented 11 months ago

This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment.

Proxicon commented 2 months ago

I have the same issue:

`ModuleType Version Name


Script 3.5.0 ExchangeOnlineManagement Script 2.23.0 Microsoft.Graph.Authentication Manifest 3.1.0.0 Microsoft.PowerShell.Management Manifest 3.1.0.0 Microsoft.PowerShell.Utility Script 1.4.8.1 PackageManagement Script 2.2.1 PowerShellGet Script 1.2 PSReadline`

On server 2016 $PSVersionTable

`Name Value


PSVersion 5.1.14393.7254 PSEdition Desktop PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.14393.7254 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1`

Steps to re produce, import Mg then Exchange connection with fail.

` $Param_ConnectMgGraph = @{ ApplicationId = 'Appid' Tenantid = 'TenantId' CertificateThumbPrint = 'certthumbprint' Verbose = $true }

Connect-MgGraph @Param_ConnectMgGraph

Welcome to Microsoft Graph!

Connected via apponly access using 98b99ef7-20d4-4729-b06a-e8fc29399eb0
Readme: https://aka.ms/graph/sdk/powershell
SDK Docs: https://aka.ms/graph/sdk/powershell/docs
API Docs: https://aka.ms/graph/docs

NOTE: You can use the -NoWelcome parameter to suppress this message.

$Param_ConnectExchangeOnline = @{
    ApplicationId         = 'Appid'
    Tenantid              = 'TenantId'
    CertificateThumbPrint = 'certthumbprint'
    Verbose               = $true
}

Connect-ExchangeOnline @Param_ConnectExchangeOnline

VERBOSE: Returning precomputed version info: 3.5.0
VERBOSE: ModuleVersion: 3.5.0
VERBOSE: ConnectionContext Removed
IDX12729: Unable to decode the header '[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' as Base64Url encoded string.
At C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.5.0\netFramework\ExchangeOnlineManagement.psm1:762 char:21
+                     throw $_.Exception.InnerException;
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : IDX12729: Unable to decode the header '[PII of type 'System.String' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' as Base64Url encoded string.`

Cant disconnect or Remove-Moduke -force need to close the exe and start it again.

In reverse: (exchange first then Mg) `Windows PowerShell Copyright (C) 2016 Microsoft Corporation. All rights reserved.

$Param_ConnectExchangeOnline = @{ AppId = "Appid" Organization = "org.onmicrosoft.com" CertificateThumbPrint = 'certthumbprint' Verbose = $true }

Connect-ExchangeOnline @Param_ConnectExchangeOnline

VERBOSE: Computed version info: 3.5.0 VERBOSE: ModuleVersion: 3.5.0 VERBOSE: [ThreadID: #] Trying to get a new token from AAD VERBOSE: [ThreadID: #] Trying to acquire token based on UI flow VERBOSE: [ThreadID: #] Successfully acquired new token for Cert based flow. VERBOSE: [ThreadID: #] Successfully got a token from AAD


This V3 EXO PowerShell module contains new REST API backed Exchange Online cmdlets which doesn't require WinRM for Client-Server communication. You can now run these cmdlets after turning off WinRM Basic Auth in your client ma chine thus making it more secure.

Unlike the EXO* prefixed cmdlets, the cmdlets in this module support full functional parity with the RPS (V1) cmdlets.

V3 cmdlets in the downloaded module are resilient to transient failures, handling retries and throttling errors inherently.

REST backed EOP and SCC cmdlets are also available in the V3 module. Similar to EXO, the cmdlets can be run without WinRM basic auth enabled.

For more information check https://aka.ms/exov3-module

VERBOSE: AutoGen EXOModule created at C:\Users\USER\AppData\Local\Temp\tmpEXO_vnasznop.0e2 VERBOSE: Running Configure-AppSettings VERBOSE: Setting PrintWarningsReceivedFromServer to False VERBOSE: PageSizes is set to: 1000 VERBOSE: Logs location is reset to C:\Users\USER\AppData\Local\Temp\EXOCmdletTelemetry VERBOSE: Max directory size reset to 2000000000 VERBOSE: Max log size reset to 100000000 VERBOSE: Log level reset to Default VERBOSE: Logger reset to null. VERBOSE: TrackPerformance is set to: False VERBOSE: ShowProgress is set to: False VERBOSE: UseMultithreading is set to: True

$Param_ConnectMgGraph = @{ ApplicationId = 'Appid' Tenantid = 'Tenant' CertificateThumbPrint = 'certthumbprint' Verbose = $true }

Connect-MgGraph @Param_ConnectMgGraph Connect-MgGraph : The 'Connect-MgGraph' command was found in the module 'Microsoft.Graph.Authentication', but the module could not be loaded. For more information, run 'Import-Module Microsoft.Graph.Authentication'. At line:1 char:5

Import-Module Microsoft.Graph.Authentication Import-Module : Could not load file or assembly 'file:///C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.5.0\netFramework\Azure.Core.dll' or one of its dependencies. The system cannot find the file specified. At line:1 char:1