JustinGrote / JAz.PIM

MIT License
30 stars 2 forks source link

Enable-JAzADRole: Unexpected exception occurred while authenticating the request #4

Closed janegilring closed 2 years ago

janegilring commented 2 years ago

I´m getting "Unexpected exception occurred while authenticating the request" when trying to activate a role:

Enable-JAzADRole                                                                              

cmdlet Enable-JAzADRole at command pipeline position 1
Supply values for the following parameters:
RoleName: Global Administrator
InvalidArgument: /home/vscode/.local/share/powershell/Modules/JAz.PIM/0.0.3/Public/Enable-ADRole.ps1:91:13
Line |
  91 |              [Guid]$roleGuid = $RoleName -replace $guidExtractRegex -a …
     |              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot convert null to type "System.Guid".

Invoke-MgGraphRequest: /home/vscode/.local/share/powershell/Modules/JAz.PIM/0.0.3/Public/Get-ADRole.ps1:20:22
Line |
  20 |          $response = (Invoke-MgGraphRequest -Uri $requestUri).value
     |                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Code: generalException Message: Unexpected exception occurred while authenticating the request. 

Exception: /home/vscode/.local/share/powershell/Modules/JAz.PIM/0.0.3/Public/Enable-ADRole.ps1:94:31
Line |
  94 |  … ot $Role) { throw "RoleGuid $roleGuid from $RoleName was not found as …
     |                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | RoleGuid 00000000-0000-0000-0000-000000000000 from Global Administrator was not found as an eligible role for this user

I`ve tried against two different tenants (in two separate dev-containers).

Before running the command, I ran this and consented the request:

Connect-MgGraph -Scopes 'RoleEligibilitySchedule.ReadWrite.Directory'

Any ideas on the root cause for this issue?

JustinGrote commented 2 years ago

That's not how rolename works, you need to tab complete or pipe because it fetches a guid, please see the quickstart and the help documentation. I'll make this error more friendly, and I'll consider adding some "search" handling here for role names.

janegilring commented 2 years ago

Ah, I see.

For some reason, tab-completion didn`t work for the Enable-JAzADRole command (although it worked fine for Enable-JAzRole): image

I suspect the reason is related to the fact that Get-JAzADRole fails so it can`t get the information needed to tab-complete:

❯ Get-JAzADRole                 
Invoke-MgGraphRequest: /home/vscode/.local/share/powershell/Modules/JAz.PIM/0.0.3/Public/Get-ADRole.ps1:20:22
Line |
  20 |          $response = (Invoke-MgGraphRequest -Uri $requestUri).value
     |                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Code: generalException Message: Unexpected exception occurred while authenticating the request. 
JustinGrote commented 2 years ago

Yeah I don't handle for the error case where you haven't logged in to graph yet for the tab completion, I'll make that a separate issue.

janegilring commented 2 years ago

I also tried to connect with both of the scopes mentioned in the readme-file:

Connect-MgGraph -Scopes 'RoleEligibilitySchedule.ReadWrite.Directory','RoleManagement.ReadWrite.Directory'

But the "generalException Message: Unexpected exception occurred while authenticating the request." error still occurs when running Get-JAzADRole.

I can do some more testing against other tenants as well to see if it is something related to the specific one I am testing against.

JustinGrote commented 2 years ago

@janegilring are you doing azure lighthouse or something? I haven't tested that scenario. If you want to do a get-error on the generalException or otherwise return the content response body that would help, I never saw that personally.

JustinGrote commented 2 years ago

The GUID part is fixed and released as v0.0.4, I'll leave this issue open for the auth issue though.

janegilring commented 2 years ago

I also gave this a try in order to find required permission scopes (as suggested in the official docs):

Find-MgGraphCommand -command Get-MgRoleManagementEntitlementManagementRoleEligibilitySchedule | Select -First 1 -ExpandProperty Permissions

However, it didn`t return anything unfortunately.

janegilring commented 2 years ago

@janegilring are you doing azure lighthouse or something? I haven't tested that scenario. If you want to do a get-error on the generalException or otherwise return the content response body that would help, I never saw that personally.

No Lighthouse, just a regular scenario.

Get-Error

Exception             : 
    Type           : Microsoft.Graph.Auth.AuthenticationException
    Error          : Code: generalException
                     Message: Unexpected exception occurred while authenticating the request.

    TargetSite     : 
        Name          : MoveNext
        DeclaringType : Microsoft.Graph.Auth.DeviceCodeProvider+<GetNewAccessTokenAsync>d__14, Microsoft.Graph.Auth, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
        MemberType    : Method
        Module        : Microsoft.Graph.Auth.dll
    Message        : Code: generalException
                     Message: Unexpected exception occurred while authenticating the request.

    InnerException : 
        Type       : System.NullReferenceException
        TargetSite : 
            Name          : WaitOurTurn
            DeclaringType : Microsoft.Graph.PowerShell.Authentication.Helpers.CustomAsyncCommandRuntime, Microsoft.Graph.Authentication, Version=1.9.6.0, Culture=neutral, 
PublicKeyToken=31bf3856ad364e35
            MemberType    : Method
            Module        : Microsoft.Graph.Authentication.dll
        Message    : Object reference not set to an instance of an object.
        Source     : Microsoft.Graph.Authentication
        HResult    : -2147467261
        StackTrace : 
   at Microsoft.Graph.PowerShell.Authentication.Helpers.CustomAsyncCommandRuntime.WaitOurTurn()
   at Microsoft.Graph.PowerShell.Authentication.Helpers.CustomAsyncCommandRuntime.WriteObject(Object sendToPipeline)
   at Microsoft.Graph.PowerShell.Authentication.Helpers.AuthenticationHelpers.<>c.<GetAuthProvider>b__2_1(DeviceCodeResult result)
   at Microsoft.Identity.Client.Internal.Requests.DeviceCodeRequest.ExecuteAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenWithDeviceCodeParameters 
deviceCodeParameters, CancellationToken cancellationToken)
   at Microsoft.Graph.Auth.DeviceCodeProvider.GetNewAccessTokenAsync(CancellationToken cancellationToken, AuthenticationProviderOption msalAuthProviderOption)
    Source         : Microsoft.Graph.Auth
    HResult        : -2146233088
    StackTrace     : 
   at Microsoft.Graph.Auth.DeviceCodeProvider.GetNewAccessTokenAsync(CancellationToken cancellationToken, AuthenticationProviderOption msalAuthProviderOption)
   at Microsoft.Graph.Auth.DeviceCodeProvider.AuthenticateRequestAsync(HttpRequestMessage httpRequestMessage)
   at Microsoft.Graph.AuthenticationHandler.SendAsync(HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, 
CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at Microsoft.Graph.PowerShell.Authentication.Cmdlets.InvokeMgGraphRequest.GetResponseAsync(HttpClient client, HttpRequestMessage request)
   at Microsoft.Graph.PowerShell.Authentication.Cmdlets.InvokeMgGraphRequest.ProcessRecordAsync()
CategoryInfo          : InvalidOperation: (:) [Invoke-MgGraphRequest], AuthenticationException
FullyQualifiedErrorId : NotSpecified,Microsoft.Graph.PowerShell.Authentication.Cmdlets.InvokeMgGraphRequest
InvocationInfo        : 
    MyCommand        : Invoke-MgGraphRequest
    ScriptLineNumber : 20
    OffsetInLine     : 22
    HistoryId        : 48
    ScriptName       : /home/vscode/.local/share/powershell/Modules/JAz.PIM/0.0.3/Public/Get-ADRole.ps1
    Line             : $response = (Invoke-MgGraphRequest -Uri $requestUri).value

    PositionMessage  : At /home/vscode/.local/share/powershell/Modules/JAz.PIM/0.0.3/Public/Get-ADRole.ps1:20 char:22
                       +         $response = (Invoke-MgGraphRequest -Uri $requestUri).value
                       +                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    PSScriptRoot     : /home/vscode/.local/share/powershell/Modules/JAz.PIM/0.0.3/Public
    PSCommandPath    : /home/vscode/.local/share/powershell/Modules/JAz.PIM/0.0.3/Public/Get-ADRole.ps1
    InvocationName   : Invoke-MgGraphRequest
    CommandOrigin    : Internal
ScriptStackTrace      : at Get-ADRole<Process>, /home/vscode/.local/share/powershell/Modules/JAz.PIM/0.0.3/Public/Get-ADRole.ps1: line 20
                        at <ScriptBlock>, <No file>: line 1
JustinGrote commented 2 years ago

Try just running this naked, it's probably something in your graph token: invoke-mggraphrequest -uri "beta/roleManagement/directory/roleEligibilitySchedules/filterByCurrentUser(on='principal')?expand=principal,roledefinition,directoryscope"

Or any of the mg cmdlets for that matter.

janegilring commented 2 years ago
invoke-mggraphrequest -uri "beta/roleManagement/directory/roleEligibilitySchedules/filterByCurrentUser(on='principal')?expand=principal,roledefinition,directoryscope"
Invoke-MgGraphRequest: Code: generalException
Message: Unexpected exception occurred while authenticating the request.

Get-MgUser
Get-MgUser_List1: Code: generalException
Message: Unexpected exception occurred while authenticating the request.

Hmmm...I`ll rebuild the whole container and try again in a purely clean environment.

janegilring commented 2 years ago

Very interesting, the same thing happens after rebuilding the container and re-authenticating.

janegilring commented 2 years ago

Now I tried in a separate environment (different AD-tenant, different dev-container) using the commands in the Quick Start:

Install-Module JAz.Pim
Import-Module JAz.Pim
Connect-AzAccount
Enable-JAzRole <tab or shift-enter>
Disable-JAzRole <tab or shift-enter>

Connect-MgGraph -Scopes 'RoleEligibilitySchedule.ReadWrite.Directory'
Select-MgProfile 'beta'
Enable-JAzADRole <tab or shift-enter>
Disable-JAzADRole <tab or shift-enter>

Still, same error - also when invoking manually:

invoke-mggraphrequest -uri "beta/roleManagement/directory/roleEligibilitySchedules/filterByCurrentUser(on='principal')?expand=principal,roledefinition,directoryscope"                                                                             
Invoke-MgGraphRequest: Code: generalException
Message: Unexpected exception occurred while authenticating the request.

I`ll look into some general usage of the Graph commands, as this is likely something related to my setup rather than the 3 different AD tenants I have tested against.

janegilring commented 2 years ago

It seems like I was hitting kind of an edge case: https://github.com/microsoftgraph/msgraph-sdk-powershell/issues/1065

After using the suggested workaround of adding -ContextScope Process to Connect-MgGraph:

Connect-MgGraph -Scopes 'RoleEligibilitySchedule.ReadWrite.Directory' -ContextScope Process

It worked like a charm:

❯ Get-JAzADRole

PrincipalDisplayName  RoleName             Scope     MemberType EndDateTime
--------------------  --------             -----     ---------- -----------
Admin - Jan Egil Ring Global Administrator Directory Direct