# Grant API permissions

## Managed identity <a href="#managed-identity" id="managed-identity"></a>

We need to grant API permissions to the service principal object in Azure. For a managed identity, this can only be done with PowerShell at the time of writing.

Run the following PowerShell code to grant API permissions. You need the **Microsoft Graph PowerShell SDK** and an account with **Global administrator** or **Application administrator** permissions.

Set the following variables in the script:

* **TenantID**. This is the tenant ID for your tenant.
* **EnterpriseAppName**. The display name of your managed identity, which is the same as the name of your automation account.
* **RolesToAssign**. Here you can list which permissions you want to grant. You can reference the [MS Docs](https://docs.microsoft.com/en-us/graph/permissions-reference) to find the permissions you need. As a minimum, the following permissions are needed for this report:
  * DeviceManagementManagedDevices.Read.All
  * DeviceManagementConfiguration.Read.All
  * DeviceManagementApps.Read.All

{% hint style="info" %}
Note these are **application** permissions not **delegated** permissions
{% endhint %}

```powershell
# Tenant Id
$TenantId = "<MyTenantId>"
# List of permission names
$RolesToAssign = @(
    "DeviceManagementManagedDevices.Read.Alll"
    "DeviceManagementConfiguration.Read.All"
    "DeviceManagementApps.Read.All"
)
#  DisplayName of the Managed Identity (Enterprise app, Service principal) you are assigning permissions to
$EnterpriseAppName = "<MyAppName>"
# Connect to Graph
Import-Module Microsoft.Graph.Applications
Connect-Graph -TenantId $TenantId -NoWelcome
# Get the service principals
$GraphApp = Get-MgServicePrincipal -Filter "AppId eq '00000003-0000-0000-c000-000000000000'" # Microsoft Graph
$EnterpriseApp = Get-MgServicePrincipal -Filter "DisplayName eq '$EnterpriseAppName'"
# Assign the roles
foreach ($Role in $RolesToAssign) {
    $Role = $GraphApp.AppRoles | Where-Object { $_.Value -eq $Role }
    $params = @{
        principalId = $EnterpriseApp.Id
        resourceId = $GraphApp.Id
        appRoleId = $Role.Id
    }
    New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $EnterpriseApp.Id -BodyParameter $params
}
```

Once granted, you will find these permissions listed against the **Enterprise application** for your managed identity in the **Permissions** pane.

![](https://3886807721-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MWe9ieepRHnj7T8odXt%2F-MdarLkZkUUPVfFwGAQZ%2F-Mdax5aEzdXbftErsmQ4%2Fimage.png?alt=media\&token=68462610-52ea-4c4b-8553-0a49b1d0e4b9)
