Saba Far
Saba Far

Reputation: 133

How to grant admin consent to an Azure AAD app in Powershell?

I'm trying to authenticate an Azure Web App using Azure Active directory. I have taken the following steps, so far:

1- Through Azure portal, I have created an app registration in AAD, and assigned it to the web app following the instructions from here.

2- I assigned some users to my app using New-AzureADGroupAppRoleAssignment cmdlet, and then set user assignment as a requirement, using set-AzureADServicePrincipal -AppRoleAssignmentRequired $true

This works as expected: the users who are not assigned to the app, see an "access denied" page, and the ones who are, see a prompt page for "Admin consent".

The problem is there is no links in the admin consent prompt for them to request it. I tried to follow the instructions from here, but I don't have access to the AAD through the portal. I can only do this through Powershell.

If you know of the Powershell cmdlet for setting this link (or to change the admin consent to user consent), I would be grateful if you could post it here.

Upvotes: 4

Views: 13318

Answers (5)

Dmitriy Ivanov
Dmitriy Ivanov

Reputation: 1300

Unfortunately, it's tricky. Not comparable to "press a button" in the Azure Portal.

Here is the PowerShell function that works:

using namespace System.Collections.Generic
function Grant-AdminConsentToAllPermissions {
    param(
        [string]$AppDisplayName
    )

    $App = Get-MgApplication -Filter "DisplayName eq '$AppDisplayName'"

    $sp = Get-MgServicePrincipal -Filter "AppId eq '$($App.AppId)'"

    foreach ($resourceAccess in $App.RequiredResourceAccess) {
        $resourceSp = Get-MgServicePrincipal -Filter "AppId eq '$($resourceAccess.ResourceAppId)'"
        if (!$resourceSp) {
            throw "Please cleanup permissions in the Azure portal for the app '$App.AppId', it contains permissions for removed App."
        }
        $scopesIdToValue = @{}
        $resourceSp.PublishedPermissionScopes | % { $scopesIdToValue[$_.Id] = $_.Value }
        [HashSet[string]]$requiredScopes = $resourceAccess.ResourceAccess | % { $scopesIdToValue[$_.Id] }
        $grant = Get-MgOauth2PermissionGrant -Filter "ClientId eq '$($sp.Id)' and ResourceId eq '$($resourceSp.Id)'"
        $newGrantRequired = $true
        if ($grant) {
            [HashSet[string]]$grantedScopes = $grant.Scope.Split(" ")
            if (!$requiredScopes.IsSubsetOf($grantedScopes)) {
                Write-Host "Revoking grant for '$($resourceSp.DisplayName)'"
                Remove-MgOauth2PermissionGrant -OAuth2PermissionGrantId $grant.Id
            }
            else {
                $newGrantRequired = $false
            }
        }
        if ($newGrantRequired) {

            $consentExpiry = ([datetime]::Now.AddYears(10)) 
            $scopesToGrant = $requiredScopes -join " "
            Write-Host "Issuing grant for '$($resourceSp.DisplayName)', scope = $scopesToGrant"
            New-MgOauth2PermissionGrant -ClientId $sp.Id -ConsentType "AllPrincipals" `
                -ResourceId $resourceSp.Id -Scope $scopesToGrant `
                -ExpiryTime $consentExpiry | Out-Null
        }
    }
}

Upvotes: 2

SvenAelterman
SvenAelterman

Reputation: 1662

This PowerShell function (inspired by https://f12.hu/2021/01/13/grant-admin-consent-to-an-azuread-application-via-powershell/) does the job.

The ApplicationID parameter is the object ID of the app registration. The context is from Get-AzContext.

function Set-AdminConsent {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$applicationId,
        # The Azure Context]
        [Parameter(Mandatory)]
        [object]$context
    )

    $token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate(
        $context.Account, $context.Environment, $context.Tenant.Id, $null, "Never", $null, "74658136-14ec-4630-ad9b-26e160ff0fc6")
    $headers = @{
        'Authorization'          = 'Bearer ' + $token.AccessToken
        'X-Requested-With'       = 'XMLHttpRequest'
        'x-ms-client-request-id' = [guid]::NewGuid()
        'x-ms-correlation-id'    = [guid]::NewGuid()
    }

    $url = "https://main.iam.ad.ext.azure.com/api/RegisteredApplications/$applicationId/Consent?onBehalfOfAll=true"
    Invoke-RestMethod -Uri $url -Headers $headers -Method POST -ErrorAction Stop
}

Upvotes: -2

Mark
Mark

Reputation: 468

After trying to get this to work with a Service Principal, which it turns out isn't possible as this can only be executed by a User account az ad app permission admin-consent --id <application-id> will be depricated in a future release as discussed on this Issue thread:

https://github.com/Azure/azure-cli/issues/12137

The advised way to grant admin consent to API's is now:

az ad app permission grant --id 46eb4122-bd2b-4f54-af7b-6d79b46ee31a 
                           --api 00000003-0000-0000-c000-000000000000
                           --scope "Directory.Read.All Directory.ReadWrite.All"

Microsoft Docs: az ad app permission grant

Upvotes: 6

Joy Wang
Joy Wang

Reputation: 42043

There is no command to grant admin consent in PowerShell currently, in your case, if you can access Azure AD with powershell, I think you can also access it via Azure CLI.

So my workaround is to use az ad app permission admin-consent in Azure CLI, it is an equivalent of the admin consent button in the portal.

Make sure you have installed the Azure CLI, use az login to login the user account or service principal which is the admin in your AAD tenant, then run the command below.

az ad app permission admin-consent --id <application-id>

Upvotes: 6

Scott Heath
Scott Heath

Reputation: 890

You have two choices. Admin consent can be granted if you have global admin permission via the portal or the AZ cli. The easiest way is via the portal. Just go to AAD, app registrations, then find your app. Go to the permissions blade. You should see a consent button. I don’t remember the AZ cli command off the top of my head, but it’s probably easier to just do it in the portal.

Upvotes: 1

Related Questions