Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connect-MgGraph -Identity -ClientId with Managed Identity contains no scopes and always throws 403 error #2763

Closed
blackadi opened this issue May 29, 2024 · 4 comments

Comments

@blackadi
Copy link

Describe the bug

encountering unusual behavior when running Graph PowerShell to fetch user signInActivity via an Azure Function HttpTrigger. I'm using a user-assigned managed identity as demonstrated here.

The managed identity service principal has all the necessary API permissions, as shown below.
image

When running the Azure Function PS Script and connecting via the user-assigned managed identity with the following cmdlet, I'm receive a 403 error:
Connect-MgGraph -Identity -ClientId "bd3dfa7c-f972-4284-a83c-ea371c7db267"

This is the logs from -Debug
`2024-05-29T13:46:34Z [Information] OUTPUT: Welcome to Microsoft Graph!

Connected via managedidentity access using bd3dfa7c-f972-4284-a83c-ea371c7db267
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.
2024-05-29T13:46:35Z [Verbose] DEBUG: [CmdletBeginProcessing]: - Get-MgUser begin processing with parameterSet 'List'.
2024-05-29T13:46:35Z [Verbose] DEBUG: [Authentication]: - AuthType: 'ManagedIdentity', TokenCredentialType: 'ManagedIdentity', ContextScope: 'Process', AppName: 'manage-identity-test'.
2024-05-29T13:46:35Z [Verbose] DEBUG: [Authentication]: - Scopes: [].
2024-05-29T13:46:35Z [Verbose] DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://graph.microsoft.com/v1.0/users?$filter=userPrincipalName eq %27addi%40addidev.site%27&$select=displayName%2CuserPrincipalName%2CsignInActivity

Headers:
FeatureFlag : 00000043
Cache-Control : no-store, no-cache
User-Agent : Mozilla/5.0,(Windows NT 10.0; Microsoft Windows 10.0.14393; en-US),PowerShell/7.2.19
Accept-Encoding : gzip
SdkVersion : graph-powershell/2.19.0
client-request-id : 02dc0672-acad-4c6a-a238-760c5c967722

Body:
2024-05-29T13:46:35Z [Verbose] DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
Forbidden

Headers:
Cache-Control : no-cache
Vary : Accept-Encoding
Strict-Transport-Security : max-age=31536000
request-id : 5a0166f3-0078-41b7-9483-535300d5835a
client-request-id : 02dc0672-acad-4c6a-a238-760c5c967722
x-ms-ags-diagnostic : {"ServerInfo":{"DataCenter":"UK South","Slice":"E","Ring":"5","ScaleUnit":"000","RoleInstance":"LN2PEPF00005FB8"}}
x-ms-resource-unit : 1
Date : Wed, 29 May 2024 13:46:34 GMT

Body:
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"date": "2024-05-29T13:46:34",
"request-id": "5a0166f3-0078-41b7-9483-535300d5835a",
"client-request-id": "02dc0672-acad-4c6a-a238-760c5c967722"
}
}
}
`

The error message from the -Debug console indicates that the scopes are empty, and there is no option to set those scopes other than having them on the managed identity service principal, which has already been granted.

Looks like the SDK is passing empty scopes via user-assigned managed identity.
image

How can I add the needed API permissions via Graph Power Shell SDK with user-assigned managed identities?

Expected behavior

Connect with the needed scopes via user-assigned managed identities instead of getting scopes as empty.

Looks like the SDK is passing empty scopes via user-assigned managed identity.
image

How to reproduce

Connect to user-assigned managed identity and call Graph API to fetch users.

Connect-MgGraph -Identity -ClientId "bd3dfa7c-f972-4284-a83c-ea371c7db267"

$users= Get-MgUser -Filter "userPrincipalName eq '[email protected]'" -Property "displayName,userPrincipalName,signInActivity"

SDK Version

2.19.0

Latest version known to work for scenario above?

No response

Known Workarounds

No response

Debug output

Click to expand log ``` 2024-05-29T13:46:34Z [Information] OUTPUT: Welcome to Microsoft Graph!

Connected via managedidentity access using bd3dfa7c-f972-4284-a83c-ea371c7db267
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.

2024-05-29T13:46:35Z [Verbose] DEBUG: [CmdletBeginProcessing]: - Get-MgUser begin processing with parameterSet 'List'.
2024-05-29T13:46:35Z [Verbose] DEBUG: [Authentication]: - AuthType: 'ManagedIdentity', TokenCredentialType: 'ManagedIdentity', ContextScope: 'Process', AppName: 'manage-identity-test'.
2024-05-29T13:46:35Z [Verbose] DEBUG: [Authentication]: - Scopes: [].
2024-05-29T13:46:35Z [Verbose] DEBUG: ============================ HTTP REQUEST ============================

HTTP Method:
GET

Absolute Uri:
https://graph.microsoft.com/v1.0/users?$filter=userPrincipalName eq %27addi%40addidev.site%27&$select=displayName%2CuserPrincipalName%2CsignInActivity

Headers:
FeatureFlag : 00000043
Cache-Control : no-store, no-cache
User-Agent : Mozilla/5.0,(Windows NT 10.0; Microsoft Windows 10.0.14393; en-US),PowerShell/7.2.19
Accept-Encoding : gzip
SdkVersion : graph-powershell/2.19.0
client-request-id : 02dc0672-acad-4c6a-a238-760c5c967722

Body:
2024-05-29T13:46:35Z [Verbose] DEBUG: ============================ HTTP RESPONSE ============================

Status Code:
Forbidden

Headers:
Cache-Control : no-cache
Vary : Accept-Encoding
Strict-Transport-Security : max-age=31536000
request-id : 5a0166f3-0078-41b7-9483-535300d5835a
client-request-id : 02dc0672-acad-4c6a-a238-760c5c967722
x-ms-ags-diagnostic : {"ServerInfo":{"DataCenter":"UK South","Slice":"E","Ring":"5","ScaleUnit":"000","RoleInstance":"LN2PEPF00005FB8"}}
x-ms-resource-unit : 1
Date : Wed, 29 May 2024 13:46:34 GMT

Body:
{
"error": {
"code": "Authorization_RequestDenied",
"message": "Insufficient privileges to complete the operation.",
"innerError": {
"date": "2024-05-29T13:46:34",
"request-id": "5a0166f3-0078-41b7-9483-535300d5835a",
"client-request-id": "02dc0672-acad-4c6a-a238-760c5c967722"
}
}
}

2024-05-29T13:46:35Z [Error] ERROR: [Authorization_RequestDenied] : Insufficient privileges to complete the operation.

Exception :
Type : System.Exception
Message : [Authorization_RequestDenied] : Insufficient privileges to complete the operation.
HResult : -2146233088
CategoryInfo : InvalidOperation: ({ ConsistencyLevel …ty = , Headers = }:<>f__AnonymousType45`9) [Get-MgUser_List], Exception
FullyQualifiedErrorId : Authorization_RequestDenied,Microsoft.Graph.PowerShell.Cmdlets.GetMgUser_List
ErrorDetails : Insufficient privileges to complete the operation.

                    Status: 403 (Forbidden)
                    ErrorCode: Authorization_RequestDenied
                    Date: 2024-05-29T13:46:34                       

                    Headers:
                    Cache-Control                 : no-cache
                    Vary                          : Accept-Encoding
                    Strict-Transport-Security     : max-age=31536000
                    request-id                    : 5a0166f3-0078-41b7-9483-535300d5835a
                    client-request-id             : 02dc0672-acad-4c6a-a238-760c5c967722
                    x-ms-ags-diagnostic           : {"ServerInfo":{"DataCenter":"UK South","Slice":"E","Ring":"5","ScaleUnit":"000","RoleInstance":"LN2PEPF00005FB8"}}
                    x-ms-resource-unit            : 1
                    Date                          : Wed, 29 May 2024 13:46:34 GMT              

InvocationInfo :
MyCommand : Get-MgUser_List
ScriptLineNumber : 14
OffsetInLine : 1
HistoryId : 1
ScriptName : C:\home\site\wwwroot\HttpTrigger1\run.ps1
Line : $test = Get-MgUser -Filter "userPrincipalName eq '[email protected]'" -Property "displayName,userPrincipalName,signInActivity" -Debug

PositionMessage  : At C:\home\site\wwwroot\HttpTrigger1\run.ps1:14 char:1

                   + $test = Get-MgUser -Filter "userPrincipalName eq '[email protected]'" …
                   + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PSScriptRoot     : C:\home\site\wwwroot\HttpTrigger1
PSCommandPath    : C:\home\site\wwwroot\HttpTrigger1\run.ps1
InvocationName   : Get-MgUser
CommandOrigin    : Internal

ScriptStackTrace : at Get-MgUser, C:\home\data\ManagedDependencies\2405291045330267851.r\Microsoft.Graph.Users\2.19.0\exports\ProxyCmdletDefinitions.ps1: line 18508
at , C:\home\site\wwwroot\HttpTrigger1\run.ps1: line 14
PipelineIterationInfo :

2024-05-29T13:46:35Z [Verbose] DEBUG: [CmdletEndProcessing]: - Get-MgUser end processing.

</details>


### Configuration

Azure Function PowerShell via HttpTrigger 

### Other information

_No response_
@blackadi blackadi added status:waiting-for-triage An issue that is yet to be reviewed or assigned type:bug A broken experience labels May 29, 2024
@petrhollayms
Copy link

Hi @blackadi ,

Thank you for raising this and for the useful screenshots, too!
Could you please try running Get-MgContext cmdlet after the connect to confirm the Scopes?

@petrhollayms petrhollayms self-assigned this May 29, 2024
@petrhollayms petrhollayms added status:waiting-for-author-feedback Issue that we've responded but needs author feedback to close and removed status:waiting-for-triage An issue that is yet to be reviewed or assigned labels May 29, 2024
@blackadi
Copy link
Author

blackadi commented Jun 4, 2024

@petrhollayms The issue has been resolved. The managed identity service principal was not syncing the latest API changes, but it is now functioning correctly.

@microsoft-github-policy-service microsoft-github-policy-service bot added Needs: Attention 👋 and removed status:waiting-for-author-feedback Issue that we've responded but needs author feedback to close labels Jun 4, 2024
@blackadi blackadi closed this as completed Jun 4, 2024
@Mwalima
Copy link

Mwalima commented Jun 19, 2024

I Am facing the same problem but in Automation account:
All modules are up to date. Imported Ms.Graph etc. and using System assignd
image

using
image

image

image

but still not enough privileges. What am i doing wrong.

@blackadi
Copy link
Author

@Mwalima make sure you add the required Graph API permissions to your service principal object ID.

To change permissions for a service principal, you need to use Graph API, either with Graph SDKs like PowerShell or with direct RESTFul calls.

  • Graph API:

    • Use GET request to call this API https://graph.microsoft.com/v1.0/servicePrincipals(appId='00000003-0000-0000-c000-000000000000')?$select=id,appRoles which will return the app roles for Microsoft Graph.
    • Then, assign these roles to the managed identity service principal using this POST request:
    POST https://graph.microsoft.com/v1.0/servicePrincipals/<managed_identity_SP_objectId>/appRoleAssignedTo
         {
              "principalId": "<managed_identity_SP_objectId>",
              "resourceId": "<MS_Graph_SP_objectId>",
              "appRoleId": "<appRoleId_returned_from_first_request>"
         }
  • Graph PowerShell:

    Connect to Graph with these scopes: "AppRoleAssignment.ReadWrite.All", "Application.Read.All"
    # Assign Graph application permissions to managed identity (outside of Azure Automation)
    $spID = "managed_identity_SP_objectId" #Managed Identity SP
    # The Graph API permissions you need to assign to your managed identity, for example User.Read.All
    $PermissionName = " GRAPH_API_PERMISSIONS" 
    $GraphServicePrincipal = Get-MgServicePrincipal -Filter "startswith(DisplayName,'Microsoft Graph')" | Select-Object -first 1 #Graph App ID: 00000003-0000-0000-c000-000000000000
    #Create a new app role assignment for the managed identity: 
    New-MgServicePrincipalAppRoleAssignment -AppRoleId $AppRole.Id -ServicePrincipalId $spID -ResourceId $GraphServicePrincipal.Id -PrincipalId $spID
    #Check the app role assignments for the managed identity: 
    $AppRoleAssignments = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $spID

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

No branches or pull requests

3 participants