Code/Function/Public/Remove-MGApplicationAPIPermission.ps1

Function Remove-MGApplicationAPIPermission {
    <#
        .SYNOPSIS
        This function removes API permission to azure ad application.
 
        .DESCRIPTION
        This function removes API permission to a azure ad application. It also automatically ungrants the permission.
 
        .PARAMETER ApplicationId
        ID of the application which will get lose permissions.
 
        .PARAMETER ApplicationAPIPermissionId
        ID of the removed permission. You can find those permissions with this command: Find-MgGraphPermission
 
        .PARAMETER Wait
        The wait parameter must be used in loops and scripts.
        If you do not use this parameter the function will exceed before the new permissions are set in azure ad.
        Otherwise the new permissions aren't set successfully.
 
        .INPUTS
        String
        Switch
 
        .OUTPUTS
        None
 
        .EXAMPLE
        Remove-MGApplicationAPIPermission -ApplicationId $Application.Id -ApplicationAPIPermissionId $_.Id -Wait
 
        .LINK
        https://github.com/gisp497/psgisp
    #>

    [CmdletBinding()]
    param (
        [Parameter(
            Mandatory = $true,
            HelpMessage = 'help message'
        )]
        [String]$ApplicationId,
        [Parameter(
            Mandatory = $true,
            HelpMessage = 'help message'
        )]
        [String]$ApplicationAPIPermissionId,
        [Parameter(
            Mandatory = $false,
            HelpMessage = 'help message'
        )]
        [Switch]$Wait = $false
    )
    Begin {
        #check authentication status
        if($null -eq (Get-MgContext)){
            Throw 'First authenticate to Microsoft Graph!'
        }

        #Get Application existing Permisisons
        $Application = Get-MgApplication -ApplicationId $ApplicationId

        #Get Service Principal for App Role
        $MGServicePrincipal = Get-MgServicePrincipal -All -Property Id,DisplayName,AppId,Approles | Where-Object{$_.AppRoles.Id -eq $ApplicationAPIPermissionId}
        if ($null -eq $MGServicePrincipal) {
            Throw ('The Application API Permissions Id: ' + $ApplicationAPIPermissionId + ' cannot be found. This function can only use Application Permission Type')
        }
        
        #Get Service Principal of App $Application
        $ApplicationServicePrincipal = Get-MgServicePrincipal -All | Where-Object {$_.AppId -eq $Application.AppId}
    }
    Process {
        #############################################
        ######Add API permission to application######
        #############################################
        #create new permissions Array
        $NewResourceAccess = @()

        ## Get the existing permissions of the application
        $ExistingResourceAccess = $Application.RequiredResourceAccess

        #Get the existing permissions of the application
        if (($ExistingResourceAccess | Where-Object {$_.ResourceAccess.Id -ne $ApplicationAPIPermissionId}).count -eq 0) {
            Update-MgApplication -ApplicationId $Application.Id -RequiredResourceAccess @{}
        }elseif ($null -ne ($Application.RequiredResourceAccess.ResourceAccess | Where-Object {$_.Id -eq $ApplicationAPIPermissionId})) {
            #set loop for every different serviceprincipal
            $ExistingResourceAccess | ForEach-Object{
                #add existing permission to hashtable and afterwards to $NewResourceAccess Variable
                if($_.ResourceAccess.Count -gt 1 -or $_.ResourceAppId -ne $MgServicePrincipal.AppId){
                    #add existing permission to hashtable and afterwards to $NewResourceAccess Variable
                    $NewResourceAccessVar = @{  
                        ResourceAppId = $_.ResourceAppId; 
                        ResourceAccess = @()
                    }
                    
                    $_.ResourceAccess | Where-Object {$_.Id -ne $ApplicationAPIPermissionId} | ForEach-Object {
                        $NewResourceAccessVar.ResourceAccess += @{ 
                            id = $_.Id;  
                            type = $_.type; 
                        }
                    }

                    $NewResourceAccess += $NewResourceAccessVar
                }
            }

            #Update Application settings
            Update-MgApplication -ApplicationId $Application.Id -RequiredResourceAccess $NewResourceAccess
        }else {
            Write-Warning ('Permission ' + $ApplicationAPIPermissionId + ' was not given')
        }

        ################################################
        ######Grant API permission for application######
        ################################################
        #Get Exsiting ServicePrincipalAppRoleAssignment
        $ServicePrincipalAppRoleAssignment = Get-MgServicePrincipalAppRoleAssignedTo -ServicePrincipalId $MgServicePrincipal.Id | Where-Object {$_.PrincipalId -eq $ApplicationServicePrincipal.Id -and $_.ResourceId -eq $MgServicePrincipal.Id -and $_.AppRoleId -eq $ApplicationAPIPermissionId}

        #check if assigment already exists
        if ($null -ne $ServicePrincipalAppRoleAssignment) {
            Remove-MgServicePrincipalAppRoleAssignedTo -ServicePrincipalId $MgServicePrincipal.Id -AppRoleAssignmentId $ServicePrincipalAppRoleAssignment.Id > $null
        }else {
            Write-Warning ('Permission ' + $ApplicationAPIPermissionId + ' was not granted')
        }

        #if Wait parameter is used, wait until new application permission are set before exiting funtion
        while ($true) {
            if ($null -eq (Get-MgApplication -ApplicationId $Application.Id | Where-Object {$_.RequiredResourceAccess.ResourceAccess.Id -eq $ApplicationAPIPermissionId})) {
                Break
            }else {
                Start-Sleep -Seconds 1
            }
        }
    }
    End {
    }
}