Add and Remove Permission in Azure App Reg – Manage Azure App Reg with PowerShell and MSGRAPH API – Part 3

That is Number 3 in this Blog Series, and now we are getting serious 🙂 The former 2 Posts have been very simple. We created an Azure App Registration and added some Secret to it. Now we take care of the Permissions, which will be a bit more complex.

Here you see the other Articles of their Series.

  • Part 1: Create and delete Azure App Regs – LINK
  • Part 2: Control Secrets in Azure App Reg – LINK
  • Part 3: Add and Remove Permission in Azure App Reg – LINK
  • Part 4: Self-Service Azure App Registration with au2mator – TBP

Prerequisites

Ensure you follow the Prerequisites in Part 1, as we need the created App Registration.

Introduction

Before we head over to the Script, I have to explain a few Details.

The tricky part is the combination of the API Name, like “Microsoft Graph,” and the corresponding permissions, like “Mail.Send”

When you add Permission in the Azure Portal, you can decide the API, then Application or Delegated Permission, followed by the Permission itself.

This also needs to be done in PowerShell, as every Permission directly connects to the API. So in our example, we focus on the API “Microsoft GRaph” and the connected Permissions. At the end of the Script is a Code to get a complete list of API and Permissions.

In Part 4 of this Series, we will see the Self-Service Solution, where you can select the API and the corresponsing Permissions in a Webfrontend.

The Script – Add Permission to Azure App Registration

To start, we configure the Authentication Details and the Script Parameters



#Graph API Details
$MSGRAPHAPI_clientID = 'yourClientID'
$MSGRAPHAPI_tenantId = 'yourTenantID'
$MSGRAPHAPI_Clientsecret = 'yourSecret'

$MSGRAPHAPI_BaseURL = "https://graph.microsoft.com/v1.0"



#Enter Azure App Details
$AzureAppName = "TestApp1"
$APIName = "Microsoft Graph" #See Code Example below to get a List of AppiNames
$ApplicationPermission = @("Mail.Send", "Mail.ReadWrite")
$DelegatedPermission = @("Mail.Send", "Mail.Send.Shared")

Now, the Authentication and Header is made


#Auth MS Graph API and Get Header
$MSGRAPHAPI_tokenBody = @{  
    Grant_Type    = "client_credentials"  
    Scope         = "https://graph.microsoft.com/.default"  
    Client_Id     = $MSGRAPHAPI_clientID  
    Client_Secret = $MSGRAPHAPI_Clientsecret  
}

$MSGRAPHAPI_tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$MSGRAPHAPI_tenantId/oauth2/v2.0/token" -Method POST -Body $MSGRAPHAPI_tokenBody  
$MSGRAPHAPI_headers = @{
    "Authorization" = "Bearer $($MSGRAPHAPI_tokenResponse.access_token)"
    "Content-type"  = "application/json"
}

And now, the exciting part comes.

First, we build an array with the delegated and Application Permissions

Next, we query the Application ID and the API Id

As we need to send the completed Permission, also including the existing one, we get the existing Permissions and then add our new one to this Array.

In the end, we send over the complete Permissions to the Azure App Registration.


#Build Array
try { [array]$ApplicationPermission = $ApplicationPermission.split(",") }
catch { [array]$ApplicationPermission = $ApplicationPermission }

try { [array]$DelegatedPermission = $DelegatedPermission.split(",") }
catch { [array]$DelegatedPermission = $DelegatedPermission }



#Get Appi from App Name
$GetIDfromName_Params = @{
    Method = "GET"
    Uri    = "$MSGRAPHAPI_BaseURL/applications?`$filter=displayName eq '$AzureAppName'"
    header = $MSGRAPHAPI_headers
}        

$GetIDfromName_Result = Invoke-RestMethod @GetIDfromName_Params


#App ID
$GetIDfromName_Result.value.id

$GetAPIID_Params = @{
    Method = "GET"
    Uri    = "$MSGRAPHAPI_BaseURL/servicePrincipals?`$filter=displayName eq '$APIName'"
    header = $MSGRAPHAPI_headers
}       


$GetAPIID_Result = Invoke-RestMethod @GetAPIID_Params

#Api ID
$GetAPIID_Result.value.id

#Get API Persmission Details
$GetSPPermissions_Params = @{
    Method = "GET"
    Uri    = "$MSGRAPHAPI_BaseURL/servicePrincipals/$($GetAPIID_Result.value.id)"
    header = $MSGRAPHAPI_headers
}
$GetSPPermissions_Result = Invoke-RestMethod @GetSPPermissions_Params


#Get actual Permission
$GetIDfromName_Result = Invoke-RestMethod @GetIDfromName_Params
$CurrentPermissions = $GetIDfromName_Result.value.requiredResourceAccess.resourceAccess


#Get and Set Application Permission
foreach ($AppPerm in $ApplicationPermission) {
    #Get AppRole Object
    $appRoleObject = $GetSPPermissions_Result.appRoles | Where-Object { $_.value -eq $AppPerm }

    if ($appRoleObject) {
                   
        #Build PSOBject with New Permissions
        $item = New-Object PSObject
        $item | Add-Member -type NoteProperty -Name 'id' -Value "$($appRoleObject.id)"
        $item | Add-Member -type NoteProperty -Name 'type' -Value "Role"

        #Check to not add duplicate Permissions
        if ($Null -eq $CurrentPermissions) {
            $CurrentPermissions = @()
            $CurrentPermissions += $item

        }
        if (!($CurrentPermissions | Where-Object { $_.id -eq $($appRoleObject.id) }) ) {
            $CurrentPermissions += $item
        }      
    }
}

#Get and Set Delegated Permission
foreach ($AppPerm in $DelegatedPermission) {
    #Get AppRole Object
    $appRoleObject = $GetSPPermissions_Result.oauth2PermissionScopes | Where-Object { $_.value -eq $AppPerm }

    if ($appRoleObject) {
                   
        #Build PSOBject with New Permissions
        $item = New-Object PSObject
        $item | Add-Member -type NoteProperty -Name 'id' -Value "$($appRoleObject.id)"
        $item | Add-Member -type NoteProperty -Name 'type' -Value "Scope"

        #Check to not add duplicate Permissions
        if ($Null -eq $CurrentPermissions) {
            $CurrentPermissions = @()
            $CurrentPermissions += $item
            

        }
        if (!($CurrentPermissions | Where-Object { $_.id -eq $($appRoleObject.id) }) ) {
            $CurrentPermissions += $item
        }    
    }
}



#Build Body to add new Permissions and keep the old ones
$SetPermissions_Body = @"
 {
     "requiredResourceAccess":[
                                 {
                                 "resourceAppId":"$($GetAPIID_Result.value.appId)",
                                 "resourceAccess":  $($CurrentPermissions |ConvertTo-Json)
                                 }
                                 ]
}
"@

#Build Parameters for Invoke
$SetPermissions_Params = @{
    Method = "PATCH"
    Uri    = "$MSGRAPHAPI_BaseURL/applications/$($GetIDfromName_Result.value.id)"
    header = $MSGRAPHAPI_headers
    body   = $SetPermissions_Body
}



#Invoke and wait
Invoke-RestMethod @SetPermissions_Params

Summary

So, we can now add and remove Permissions with Powershell. We are one step further to managing Azure App Registrations with Powershell ultimately.

GitHub

See the Script in GitHub: https://github.com/Seidlm/Microsoft-Azure

– Add API Permissions to Azure App Reg.ps1

Michael Seidl aka Techugy
au2mate everything

2 thoughts on “Add and Remove Permission in Azure App Reg – Manage Azure App Reg with PowerShell and MSGRAPH API – Part 3”

  1. Pingback: Control Secrets in Azure App Reg - Manage Azure App Reg with PowerShell and MSGRAPH API - Part 2 - TechGuy

  2. Pingback: Create and delete Azure App Regs - Manage Azure App Reg with PowerShell and MSGRAPH API - Part 1 - TechGuy

Leave a Comment

Your email address will not be published. Required fields are marked *

*