DEV Community

Kinga for Software Development

Posted on

Grant API Permissions with Microsoft.Graph

Granting API Permissions to Managed Identity can only be done using PowerShell.
In the past, we did it using AzureRM PowerShell modules, but since it will be retired in 29 February 2024, it's time to update the scripts to Az.

The Az.Resources PowerShell module 5.1.0+ introduces changes to the identity-related cmdlets, with the cmdlets relying on Azure AD Graph transitioning to Microsoft Graph.

PowerShell Modules

If you haven't done it yet, install the Az.Resources module

Install-Module -Name Az.Resources -Repository PSGallery -Scope CurrentUser
Enter fullscreen mode Exit fullscreen mode

Sign in

In order to change app role assignments, you need to have at least AppRoleAssignment.ReadWrite.All and Application.Read.All permissions.
Specify these scopes when signing in, to make sure you can execute the script

$tenantID = "{tenant-id}"
Connect-MgGraph -TenantId $tenantID `
-Scopes "AppRoleAssignment.ReadWrite.All", "Application.Read.All"
Enter fullscreen mode Exit fullscreen mode

Grant API Permissions to Managed Identity

$spObjId = "{service-principal-object-id}"
$siteUrl = "{site-url}"

# Get Service Principal
$sp = Get-MgServicePrincipal -ServicePrincipalId  $spObjId

### STEP 1: GRANT API PERMISSIONS TO MANAGED IDENTITY

#Retrieve the Azure AD Service Principal instance for the Microsoft Graph (00000003-0000-0000-c000-000000000000) or SharePoint Online (00000003-0000-0ff1-ce00-000000000000).
$servicePrincipal_Graph = Get-MgServicePrincipal -Filter "DisplayName eq 'Microsoft Graph'"
$servicePrincipal_SPO = Get-MgServicePrincipal -Filter "DisplayName eq 'Office 365 SharePoint Online'"

#Get AppRole Id for Sites.Selected
$appRole_GraphId = ($servicePrincipal_Graph.AppRoles | Where-Object { $_.AllowedMemberTypes -eq "Application" -and $_.Value -eq "Sites.Selected" }).Id
$appRole_SPOId = ($servicePrincipal_SPO.AppRoles | Where-Object { $_.AllowedMemberTypes -eq "Application" -and $_.Value -eq "Sites.Selected" }).Id

# Grant API Permissions
$graphParams = @{
    principalId = $sp.Id
    resourceId  = $servicePrincipal_Graph.Id
    appRoleId   = $appRole_GraphId
}
$spoParams=@{
    principalId = $sp.Id
    resourceId  = $servicePrincipal_SPO.Id
    appRoleId   = $appRole_SPOId
}
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $sp.Id -BodyParameter $graphParams
New-MgServicePrincipalAppRoleAssignment  -ServicePrincipalId $sp.Id -BodyParameter $spoParams
Enter fullscreen mode Exit fullscreen mode

Quick check if everything went well

Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $sp.Id
Enter fullscreen mode Exit fullscreen mode

You may find the script here

Top comments (0)