Programmatically grant admin consent to a service principal

Most articles and e.g. az module commands allow you to do an admin consent on an application object.

However, Service Principals have the same option in the Azure Portal:

In my scenario I have control over both the hosting tenant of this multi-tenant app registration, so I could use the requiredResourceAccess property to read all Oauth2permissiongrants and approleAssignments from the source app registration to re-apply it to the service principal in the consuming tenant.

The result is similar to consenting through the admin portal but does not require user interaction / is fully headless, ideal for when you’re adding scopes/roles to an application and don’t want to have to do a manual reconsent in all managed tenants.

Here’s the code to to programmatic admin consent:

https://gitlab.com/Lieben/assortedFunctions/-/blob/master/grant-adminConsentForServicePrincipal.ps1

It requires DelegatedPermissionGrant.ReadWrite.All and AppRoleAssignment.ReadWrite.All graph permissions for the calling principal (user or application).

If you don’t have access to the source tenant (e.g. multi tenant), you can also simply create a hashtable with the required permissions (manual definition or export from the application manifest).

Easily get access token for Azure Management API

Wrote this little snippet that assumes a logged in session (Connect-AzAccount) and easily/quickly produces an auth header.

function get-azRMAccessHeader(){
    $profile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
    $context = Get-AzContext
    $client = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($profile)

    $header = @{
        "Authorization" = "Bearer $($client.AcquireAccessToken((Get-AzContext).Tenant.TenantId).AccessToken)"
    }
    return $header
}