Skip to content

Connect-MgGraph auth token unusable when -UseDeviceCode #3495

Description

@lsnliu

Describe the bug

I'm trying to use connect-mggraph with -UseDeviceCode. The auth is successful but all subsequent commands fail with DeviceCodeCredential authentication failed: Object reference not set to an instance of an object. All tested commands are successful without the -UseDeviceCode flag

Expected behavior

-UseDeviceCode should work

How to reproduce

  1. Connect-MgGraph -Scopes "AppRoleAssignment.ReadWrite.All", "Application.Read.All" -NoWelcome -UseDeviceCode
  2. Get-MgServicePrincipal -Filter "displayName eq 'some app name'"

SDK Version

2.34

Latest version known to work for scenario above?

Not sure, first time doing this and 2.34 was the version used.

Known Workarounds

None

Debug output

Click to expand log

PS C:\managed_identity_permissions> Get-MgServicePrincipal -Filter "displayName eq '$DisplayNameOfApp'" -debug
DEBUG: [CmdletBeginProcessing]: - Get-MgServicePrincipal begin processing with parameterSet 'List'.

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): A
DEBUG: [Authentication]: - AuthType: 'Delegated', TokenCredentialType: 'DeviceCode', ContextScope: 'CurrentUser',
AppName: 'Microsoft Graph Command Line Tools'.
DEBUG: [Authentication]: - Scopes: [Application.Read.All, Application.ReadWrite.All, AppRoleAssignment.ReadWrite.All,
DelegatedPermissionGrant.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All, Group.Read.All, openid,
Policy.Read.All, Policy.ReadWrite.PermissionGrant, profile, RoleManagement.Read.All, Sites.FullControl.All,
Synchronization.ReadWrite.All, User.Read, User.ReadWrite.All, email].
DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://graph.microsoft.com/v1.0/servicePrincipals?$filter=displayName eq 'test1'

Headers:
FeatureFlag                   : 00000003
Cache-Control                 : no-store, no-cache
User-Agent                    : Mozilla/5.0,(Windows NT 10.0; Microsoft Windows 10.0.26200;
en-AU),PowerShell/5.1.26100.7462

Body:


DEBUG: [CmdletException]: Received exception with message 'AuthenticationFailedException - DeviceCodeCredential
authentication failed: Object reference not set to an instance of an object. :    at
Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean
isCredentialUnavailable)
   at Azure.Identity.DeviceCodeCredential.<GetTokenImplAsync>d__44.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 Azure.Identity.DeviceCodeCredential.<GetTokenAsync>d__41.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.Kiota.Authentication.Azure.AzureIdentityAccessTokenProvider.<GetAuthorizationTokenAsync>d__14.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.Graph.PowerShell.Authentication.Handlers.AuthenticationHandler.<AuthenticateRequestAsync>d__13.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.Graph.PowerShell.Authentication.Handlers.AuthenticationHandler.<SendAsync>d__12.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.Graph.PowerShell.Applications.<ServicePrincipalListServicePrincipal_Call>d__1015.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Graph.PowerShell.Applications.<ServicePrincipalListServicePrincipal_Call>d__1015.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.Graph.PowerShell.Applications.<ServicePrincipalListServicePrincipal>d__1013.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.Graph.PowerShell.Cmdlets.GetMgServicePrincipal_List.<ProcessRecordAsync>d__92.MoveNext()'

Confirm
DeviceCodeCredential authentication failed: Object reference not set to an instance of an object.
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): A
Get-MgServicePrincipal : DeviceCodeCredential authentication failed: Object reference not set to an instance of an object.
At line:1 char:1
+ Get-MgServicePrincipal -Filter "displayName eq '$DisplayNameOfApp'" - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-MgServicePrincipal_List], AuthenticationFailedException
    + FullyQualifiedErrorId : Microsoft.Graph.PowerShell.Cmdlets.GetMgServicePrincipal_List

Configuration

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

Other information

No response

Activity

  1. lsnliu commented on Jan 8, 2026

    @lsnliu
    Author

    For context, device code is required as our org has a funny auth issue that prevents login of the admin account on our default browsers (it's not explicitly disallowed, just when it is completed, the redirect goes back to the normal account attached to the OS).

    As such, it must be done in private browsing and the auth pop ups from connect-mggraph can't be configured to use private browsing AFAIK.

  2. SOM-Scott commented on Jan 9, 2026

    @SOM-Scott

    Having the same issue since -Environment USGov is broken v2.34.0

  3. gavinbarron commented on Jan 12, 2026

    @gavinbarron
    Member

    lsnliu thanks for reporting this. I'll admit I'm a bit puzzled as I can still sign-in using the Device Code Flow.

    Are you running the PowerShell process as the user logged into Windows?

    Does this reproduce when running Disconnect-MgGraph followed by Connect-MgGraph or only when running additional cmdlets?

  4. lsnliu commented on Jan 13, 2026

    @lsnliu
    Author

    Gavin Barron (@gavinbarron) thanks for picking this up:

    • The issue can be reproduced reliably even after Disconnect-MgGraph
    • Connect-MgGraph has no issues and no errors. Only additional cmdlets have this issue.
    • The issue only exists when the user being used for Connect-MgGraph is NOT the same as the windows user.
    • The issue does not exist when --UseDeviceCode flag is not added, even when the user is NOT the same as the windows user.

    Hope this helps

  5. jesusfermsft commented on Jan 13, 2026

    @jesusfermsft

    I can reproduce the same with the same versions as OP.

  6. gavinbarron commented on Jan 20, 2026

    @gavinbarron
    Member

    one further clarification. I think that the PowerShell process is running as the windows user in your scenario, can you confirm/deny this?

  7. lsnliu commented on Jan 21, 2026

    @lsnliu
    Author

    Gavin Barron (@gavinbarron) if I'm understanding you correctly, I would have had to run RunAs <some user> "powershell.exe". This is not the case.

    My steps for executing my code is:

    1. windows + R, powershell
    2. cd to my directory
    3. ./scriptName.ps1

    I can also just run the commands directly in any normal powershell and reproduce this issue.

  8. wintrail7 commented on Feb 5, 2026

    @wintrail7

    I’m seeing the same behavior, with similar use cases as other commenters.

    Specifically:

    • this behavior is present in both Microsoft.Graph.Authentication 2.34 and 2.35
    • this behavior is not present in 2.33 (works correctly)
    • this behavior is present even when requesting different scopes from the original complaint—even simply User.Read.All
    • I wonder if this is an unintended consequence of requiring WAM, but resulting in no tokens for a user being accepted if not for the logged-in Windows user

    I can share more details about my environment, but I have uninstalled and reinstalled Graph modules 2.33, 2.34, and 2.35 repeatedly, using both Powershell 5.1 and 7.5.4 with the behavior well established.

  9. wintrail7 commented on Feb 5, 2026

    @wintrail7

    one further clarification. I think that the PowerShell process is running as the windows user in your scenario, can you confirm/deny this?

    Can confirm that this is the case for me. Again, this was a functional setup in 2.33 but does not properly issue or accept usable tokens in 2.34 and 2.35.

  10. juntakata commented on Feb 21, 2026

    @juntakata
    Contributor

    Gavin Barron (@gavinbarron) I can reproduce this issue in my lab environment using version 2.35.1. We started to see customer support cases to Microsoft support. If I remove -UseDeviceAuthentication option, everything works fine.

    PS C:\> Connect-MgGraph -Scopes "Application.Read.All","AppRoleAssignment.ReadWrite.All","Directory.Read.All" -UseDeviceAuthentication
    To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code E58Y4MXPD to authenticate.
    Welcome to Microsoft Graph!
    
    Connected via delegated access using 14d82eec-204b-4c2f-b7e8-296a70dab67e
    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.
    NOTE: Sign in by Web Account Manager (WAM) is enabled by default on Windows systems and cannot be disabled when using the default ClientId.
    To disable WAM run Set-MgGraphOption -DisableLoginByWAM $true and then use a custom ClientId.
    
    PS C:\> Get-MgUser
    Get-MgUser : DeviceCodeCredential authentication failed: Object reference not set to an instance of an object.
    At line:1 char:1
    + Get-MgUser
    + ~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [Get-MgUser_List], AuthenticationFailedException
        + FullyQualifiedErrorId : Microsoft.Graph.PowerShell.Cmdlets.GetMgUser_List
    
    PS C:\> Get-Module
    
    ModuleType Version    Name                                ExportedCommands
    ---------- -------    ----                                ----------------
    Script     2.35.1     Microsoft.Graph.Authentication      {Add-MgEnvironment, Connect-MgGraph, Disconnect-MgGraph, Get-MgContext...}
    Script     2.35.1     Microsoft.Graph.Users               {Get-MgUser, Get-MgUserByUserPrincipalName, Get-MgUserCount, Get-MgUserCreatedObject...}
    Manifest   3.1.0.0    Microsoft.PowerShell.Management     {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Content...}
    Manifest   3.1.0.0    Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
    Binary     1.0.0.1    PackageManagement                   {Find-Package, Find-PackageProvider, Get-Package, Get-PackageProvider...}
    Script     1.0.0.1    PowerShellGet                       {Find-Command, Find-DscResource, Find-Module, Find-RoleCapability...}
    Script     2.0.0      PSReadLine                          {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PSReadLineKeyHandler, Set-PSRe...
  11. gavinbarron commented on Feb 24, 2026

    @gavinbarron
    Member

    thanks for the additional information Jun Takata (@juntakata)

    we'll look into this and see if an additional fix can be made to enable -UseDeviceCode

    The existing workarounds of using v2.33.0 or v2.35.1 with a custom app registration are available to you until we have a solution here.

  12. md7648 commented on Mar 25, 2026

    @md7648

    So far WAM has fucked every module up when running as Admin

    In many environments you have to run ISE (yes I know) or more likely VSCode as Admin due to constrained language mode and the ease of installing modules or new code into the program

    Having to go through and find stable versions is frustrating. Device code does work for most of them but its an extra step in the process and one that shouldn't be needed.

  13. ramsessanchez commented on Mar 31, 2026

    @ramsessanchez
    Contributor

    Hi everyone, it appears that this issue is related to the bump in azure identity that we included when we made the update to use WAM by default. A change in behavior in the azure identity meant that we were no longer handling the token cache for deviceCodeAuth correctly. A fix is currently being worked on and should be available for the next release. Thanks everyone for bringing this to our attention.

  14. Null-Fault commented on Apr 22, 2026

    @Null-Fault

    It seems there is further regression. DeviceCode doesn't work with response of "DeviceCodeCredential authentication failed: Object reference not set to an instance of an object." and so does interactive until you register user with device.

  15. SteveyBoros commented on May 26, 2026

    @SteveyBoros

    Just tested 2.37.0 on Windows 11 / PowerShell 7.4 hoping #3573 had landed. It has (isCaeEnabled: true is there in AuthenticationHelpers.cs around line 294) but the original NRE still happens on the first API call after Connect.

    Just tested 2.37.0 on Windows 11 / PowerShell 7.4 hoping #3573 had landed. It has (isCaeEnabled: true is there in AuthenticationHelpers.cs around line 294) but the original NRE is still happening on the first API call after Connect.

    Connect-MgGraph -UseDeviceCode -Scopes 'User.Read.All' -ContextScope Process -NoWelcome
    # device code completes fine, Get-MgContext shows the right scope
    Get-MgUser -Top 5
    # Get-MgUser_List: DeviceCodeCredential authentication failed: Object reference not set to an instance of an object.

    I think #3573 fixed the wrong half. SignInAsync builds a DeviceCodeCredential, warms its MSAL cache with the CAE-enabled token (that's the #3573 change), and returns. When an API call runs, GetAuthenticationProviderAsync constructs a brand new DeviceCodeCredential via GetTokenCredentialAsync and wraps that in AzureIdentityAccessTokenProvider. The second credential's in-memory cache is empty, MSAL misses, it falls back to running device code silently, and NREs.

    The Process-scope cache is per-instance unless you wire up TokenCachePersistenceOptions, so what #3573 did to the first instance never benefits the second.

    Also, pinning Microsoft.Graph.Authentication to 2.33.0 doesn't avoid this either, the NRE reproduces there too. So 2.33, 2.34, 2.35.x, 2.36.x, 2.37.0 are all broken for -UseDeviceCode as far as I can see.

    Can this be reopened, or is there a newer tracking issue I should be on? The 2.37.0 release notes call #3573 the fix for this, but it isn't.

  16. DougChandler commented on Jul 1, 2026

    @DougChandler

    I hit this issue today running Microsoft.Graph v2.38.0.
    Disconnect-MgGraph and Connect-MgGraph worked but not a long-term solution.
    Please reopen to get this fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions