powershellazure-powershellmicrosoft-entra-idazure-app-registration

PATCH appRoles to existing Entra Application using PowerShell Invoke-RestMethod


I am creating BICEP resources for an automated DevOps Pipeline which automates the creation of App Registrations within Microsofts EntraID. The BICEP is using a Microsoft.Resources/deploymentScripts@2023-08-01 resource which hold a piece of script which actually invokes a powershell script within Azure Services. The basic implementation comes from Medium Automate App Registrations.

I modified the script in a way that it also adds some App Roles which must be applied on an (in this case already existing) Application (Application resource).

Currently I can create an Application and also update it with, for example, a secret, api permissions etc... The only thing that returns a BadRequest, is the update for App Roles (AppRoles Resource). I used the example given by Microsoft itself for the specific model in the PowerShell example: AppRoles update example. In my powershell I use the Azure request invocation and soo far it only responds with a BadRequest without any specific message only than 'An unexpected 'PrimitiveValue' node was found when reading from the JSON. A 'StartArray' node was expected.'. The App Roles array in the JSON content is already an array from Microsofts example.

Soo far this is my latest piece of code for the POC, which must apply the app roles. I verified that the App Registration exists. Also the configured Managed User Identity has sufficient access:

foreach ($role in $roles) {
    $splitRole = $role.Split(";")
    $roleName = $splitRole[0]
    $roleDescription = $splitRole[1]
    Write-Host "RoleName: $($roleName)"
    Write-Host "RoleDescription: $($roleDescription)"

    $appRegistration = (Invoke-RestMethod -Method GET -Headers $headers -Uri "https://graph.microsoft.com/beta/applications/$($app.id)")
    Write-Host "App Registration: $($appRegistration)"

    # Convert the JSON output to a PowerShell object
    $appRoles = $appRegistration.appRoles
    Write-Host "App Registration Roles: $($appRoles)"

    # Extract and filter the app roles based on the DisplayName
    $filteredRoles = $appRoles | Where-Object { $_.displayName -eq $roleName }
    Write-Host "App Registration filtered roles: $($filteredRoles)"

    if ($null -eq $filteredRoles) {
        Write-Host "Role not found, create new role..."

        $newAppRole = @{
            appRoles = @(
                @{
                    allowedMemberTypes = @(
                        "Application"
                    )
                    description        = $($roleDescription)
                    displayName        = $($roleName)
                    id                 = [Guid]::NewGuid()
                    isEnabled          = $false
                    origin             = "Application"
                    value              = $($roleName)
                })
        }

        Write-Host "Updated App Registration:"
        Write-Host ($newAppRole.appRoles | Format-Table | Out-String)

        Write-Host "Updated as JSON: $($newAppRole | ConvertTo-Json)"

        try {
            $createdAppRole = Invoke-RestMethod -Method PATCH -Headers $headers -Uri "https://graph.microsoft.com/beta/applications/$($app.id)" -Body ($newAppRole | ConvertTo-Json)
            Write-Host("App Registration patch result: $($createdAppRole)")
        }
        catch {
            Write-Host "Failed to patch app roles:"
            Write-Host ($_ | Format-Table | Out-String)

            Write-Host "Other properties:"
            Write-Host ($_.message)
            Write-Host ($_.message | Format-Table | Out-String)

            Write-Host ($_.Exception.Response)
            Write-Host ($_.message)
            Write-Host ($_.message)

            $_.Exception.Response

            Write-Host "Exception details: "
            $e = $_.Exception
            Write-Host ("`tMessage: " + $e.Message)
            Write-Host ("`tStatus code: " + $e.Response.StatusCode)
            Write-Host ("`tStatus description: " + $e.Response.StatusDescription)
        }
    }
}

In my logging the JSON result of the App Roles is:

{
  "appRoles": [
    {
      "origin": "Application",
      "id": "b1d3d9dd-1cf6-4e2e-bcf1-b586a2a62244",
      "displayName": "app.customers",
      "allowedMemberTypes": "Application",
      "value": "app.customers",
      "description": "System has access to all functionalities in customer module.",
      "isEnabled": false
    }
  ]
}

I am not a very good PowerShell developer, soo maybe I am doing something wrong or overlooking something stupid;-) Hopefully somebody can help.

UPDATE: I found another thread which looks similar to this question: Other thread. However, the message does not point to a specific property 'allowedMemberTypes'. Also not in the innerException. The JSON Convert does not create an array from that property. Going to try to force the ConvertTo-Json to get a real JSON array representation.

UPDATE: I noticed that I learned something new for PowerShell. Mathias R. Jessen is correct about the JSON Dept. This solved my problem. Thanks a lot!


Solution

  • I noticed that I learned something new for PowerShell. Mathias R. Jessen is correct about the JSON Dept. This solved my problem. Thanks a lot!

    The new AppRole script looks like this, with a dept great enough for future usage:

    $newAppRole = @{
    appRoles = @(
        @{
            allowedMemberTypes = @(
                "Application"
            )
            description        = $($roleDescription)
            displayName        = $($roleName)
            id                 = [Guid]::NewGuid()
            isEnabled          = $true
            origin             = "Application"
            value              = $($roleName)
        })
    }
    
    Write-Host "Updated App Registration:"
    Write-Host ($newAppRole.appRoles | Format-Table | Out-String)
    
    try {
        $createdAppRole = Invoke-RestMethod -Method PATCH -Headers $headers -Uri "https://graph.microsoft.com/beta/applications/$($app.id)" -Body ($newAppRole | ConvertTo-Json -Depth 5)
        Write-Host("App Registration patch result: $($createdAppRole)")
    }
    catch {
        Write-Host "Failed to patch app roles:"
        Write-Host ($_ | Format-Table | Out-String)
    }