Some Azure API permissions requires admin consent, which can be granted through the Azure portal.

However, sometimes it’s needed to grant such consent programmatically, especially when creating service principals via IaC.
Requirements for Granting Admin Consent
To be able to grant admin consent, the Azure AD role “Application Administrator” is required.
Granting Admin Consent through Azure CLI
When talking about API permissions we need to differentiate between delegated permissions and application permissions.

Delegated Permissions
To grant delegated permissions we can simply use of the “az ad app permission grant” Azure CLI command.
az ad app permission grant --id <Application ID of your Service Principal> --api <Application ID of the API> --scope <API Permission Name>
Application ID of your Service Principal can be found in the Overview blade of your App Registration.
Application ID of the API can be found when clicking on “Add a permission” in the App Registration API Permission blade.

API Permission Name is the name of the permission, e.g. “Directory.ReadWrite.All”.
Application Permissions
Granting consent for application permissions is a bit more complicated. Unfortunately there is no native Azure CLI command to grant consent to application permissions. Therefore, we need to make use of the “az rest” Azure CLI command, which can send REST API calls to a certain Azure API (in our case the Microsoft Graph API).
az rest --method POST --uri https://graph.microsoft.com/beta/servicePrincipals/<Object ID of the API Service Principal>/appRoleAssignments \
--header Content-Type=application/json \
--body '{
"principalId": "<Object ID of your Application>",
"resourceId": "<Object ID of the API Service Principal>",
"appRoleId": "<Permission ID of the API Permission>"
}'
Object ID of the API Service Principal can be retrieved through the following Azure CLI command. This ID varies in different tenants. 00000003-0000-0000-c000-000000000000 is the application ID of the Microsoft Graph API (same in each tenant).
az ad sp show --id 00000003-0000-0000-c000-000000000000 --query "objectId"
Object ID of your Application can be retrieved through the following Azure CLI command. 31eb5421-bd4b-5f41-af7b-7d89b62ee37a is the application ID of your service principal.
az ad sp show --id 31eb5421-bd4b-5f41-af7b-7d89b62ee37a --query "objectId"
Permission ID of the API Permission can be retrieved through the following Azure CLI command. 00000003-0000-0000-c000-000000000000 is the application ID of the Microsoft Graph API (same in each tenant). Directory.ReadWrite.All is the name of the API permission.
az ad sp show --id 00000003-0000-0000-c000-000000000000 --query "appRoles[?value=='Directory.ReadWrite.All']"