Search code examples
powershellmicrosoft-graph-apimicrosoft-entra-id

Issues with Azure permissions for Graph API


I am having issues trying to run some PowerShell scripts over my tenant, the script performs a connection to the Graph API:

Connect-MgGraph -TenantId $TenantId -ErrorAction Stop

Reads the users of a particular domain:

$Users = Get-MgUser -All -ConsistencyLevel eventual -CountVariable Count -Filter "endsWith(userPrincipalName, '$Domain')" -Select Id,UserPrincipalName,OnPremisesImmutableId -ErrorAction Stop

Then iterates over the users to determine if the OnPremisesImmutableId field exists for the user, if not, it performs a movement of the user to the @X.onmicrosoft.com domain and places it back to the main domain.

My issue is that even if the account creator runs the script we get a permissions issue:

Status: 403 (Forbidden)
ErrorCode: Authorization_RequestDenied

The user has Global Administrator role assigned at Tenant level.

Worth to mention that I've also tested this in a different tenant and I was able to run the script, this seems to be a setting in this particular tenant that prevents the execution of the desired operation.

Any advise?

Thanks in advance!


Solution

  • Independently of your roles on Entra ID, you needs to request scopes to gain permissions inside the Graph API. The list of available scopes is documented here.

    By default, the Microsoft.Graph module will request only the User.Read scope (and previous scopes you already approved before).

    You can check which scopes are being used using:

    Get-MgContext | Select -ExpandProperty Scopes
    

    The documentation of each API endpoint list the scopes that are required to access the endpoint. For example, for getting users, they are listed here: https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http#permissions

    Note: There is a similar table in the documentation of the Powershell cmdlets, but it's not up-to-date. Therefore, I recommend to reference to the Graph API documentation directly.


    Now, about your question: In order to list all the users of your tenant, including all of their properties, you'll needs to use at least the User.Read.All scope.

    As you needs to update some users, you'll also needs the User.ReadWrite.All scope.

    You can requests these scopes like this:

    Connect-MgGraph -TenantId $TenantId -Scopes "User.Read.All","User.ReadWrite.All"
    

    Or since User.ReadWrite.All already allow to get users, just:

    Connect-MgGraph -TenantId $TenantId -Scopes "User.ReadWrite.All"