Find Least Privileged Roles for Delegated Graph API Permissions

The second principle of Zero Trust is “least privileged access.” For administrators, this means you should have only the minimal amount of access necessary to complete a specific task, and ideally no more.

This principle can be challenging for administrators who want to use the Microsoft Graph API programmatically to perform tasks efficiently and accurately.

In previous blog posts, I have discussed how to identify the least privileged permissions needed for certain tasks with the Microsoft Graph API. For instance, in one blog, I demonstrated how to use the Microsoft Graph Developer Proxy to find the minimum Graph API permissions required to complete a task. Similarly, I showed how to identify the minimum Graph API permission needed for a specific cmdlet in the Microsoft Graph PowerShell SDK.

While these methods are helpful, the delegated access scenario presents an additional challenge. To access resources via Microsoft Graph in this scenario, you need a combination of admin consent for the Graph API permissions and a Microsoft Entra role that supports your access. Without the appropriate Entra role, you may lack sufficient access to complete your task, or you could end up with excessive access, making you “over-privileged.”

In this article, I will guide you through my approach to mapping Microsoft Graph API permissions to Microsoft Entra roles.

Understanding the problem

I just need to ensure that I have the minimum role assigned in Microsoft Entra to use the necessary Graph API permissions, right? That’s correct! However, the only way to determine this at the moment is through educated guesswork. Unfortunately, Microsoft does not currently provide a mapping that specifies, “For this API permission, you need at least this role.” It’s quite frustrating, to say the least.

Mapping API permissions to least privileged Entra role

What once seemed like a complex task at this time last year has become an exciting endeavor with the help of AI. The challenge lies in the fact that there are over 450 delegated Graph API permissions available as of this writing. Mapping the least privileged Microsoft Entra role requires careful thought and due diligence, as it involves comparing each permission with the descriptions of each built-in Microsoft Entra role.

The concept is quite simple: use AI to automatically perform due diligence between each API permission and Entra role programmatically, determining which role is considered the least privileged.

But how can I query AI programmatically? This is where the impressive psaisuite PowerShell module, created by Doug Finke, comes into play. This module enables me to choose a large language model (LLM) and programmatically construct requests to obtain responses. These responses can then be utilised in my shell session to create a structured table of data.

Querying the least privileged Entra role for a specific Graph API permission

Throughout these next steps, I use two PowerShell modules:

  • Microsoft.Graph.Authentication
  • psaisuite

To install these modules, run the following commands.

Install-Module Microsoft.Graph.Authentication -Scope CurrentUser
Install-Module psaisuite -Scope CurrentUser

The first step is to configure your chosen large language model (LLM) for making queries. In my case, I selected the gemini-2.5-flash-preview-04-17 model because it provided the clearest responses. The downside is that this model is in preview and subject to heavy rate limits, so I supported this work by also using gemini-2.0-flash. 

First and foremost, I need to store a couple of variables in my environment, namely, the API key for Google AI Studio and the name of the LLM.

$env:GeminiKey="API KEY HERE"
$env:PSAISUITE_DEFAULT_MODEL = "gemini:gemini-2.5-flash-preview-04-17"

Now that everything is ready, I can connect to Microsoft Graph and retrieve a list of all delegated API permissions from the Graph resource in Entra.

Connect-MgGraph -Scopes Application.Read.All

$allPermissions = Invoke-MgGraphRequest -Uri "beta/servicePrincipals(appId='00000003-0000-0000-c000-000000000000')?`$select=publishedPermissionScopes" -OutputType PSObject
$DelegatedAdminPermissions = $allPermissions.publishedPermissionScopes | Where { $_.type -eq "Admin" }

I also needed a list of all Microsoft Entra roles, as these would form the basis for the decision-making process within the LLM. They would also validate the LLM’s responses, ensuring that the returned role name is valid. While I know there are more efficient ways to obtain Entra role names through Microsoft Graph, for this exercise, I aimed to create a function that would scrape the roles from the table on the Microsoft Built-In Entra Roles webpage. I asked Claude Sonnet 3.7 to assist with this task, and here is the response I received, a perfectly working example!

function Get-EntraRolesFromWeb {
    param(
        [string]$Url = "https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference"
    )

    Write-Verbose "Downloading Entra roles information from $Url"
    try {
        $response = Invoke-WebRequest -Uri $Url -UseBasicParsing -ErrorAction Stop
    }
    catch {
        Write-Error "Failed to download from URL '$Url': $_"
        return $null
    }

    # Get the HTML content
    $htmlContent = $response.Content

    # Locate the "All roles" section and table
    $anchor = '<h2 id="all-roles">'
    $tableStartMarker = "<table"
    $tableEndMarker = "</table>"

    $anchorPos = $htmlContent.IndexOf($anchor)
    if ($anchorPos -lt 0) {
        Write-Error "Could not find the 'All roles' section on the page. The page structure might have changed."
        return $null
    }

    $tableStartPos = $htmlContent.IndexOf($tableStartMarker, $anchorPos)
    if ($tableStartPos -lt 0) {
        Write-Error "Could not find the table start marker after the 'All roles' heading."
        return $null
    }

    $tableEndPos = $htmlContent.IndexOf($tableEndMarker, $tableStartPos)
    if ($tableEndPos -lt 0) {
        Write-Error "Could not find the table end marker."
        return $null
    }

    # Extract the table HTML
    $tableHtml = $htmlContent.Substring($tableStartPos, $tableEndPos - $tableStartPos + $tableEndMarker.Length)

    # Extract table headers
    $headerMatches = [regex]::Matches($tableHtml, "<th.*?>(.*?)</th>", "IgnoreCase")
    if ($headerMatches.Count -eq 0) {
        Write-Error "Could not find table headers (<th> tags)."
        return $null
    }

    # Clean up header names for use as property names
    $headers = $headerMatches | ForEach-Object {
        $headerText = $_.Groups[1].Value.Trim()
        # Remove any HTML tags within the header
        $headerText = [regex]::Replace($headerText, "<.*?>", "").Trim()
        # Make header suitable for property name
        $headerText -replace '\s+', '' -replace '[^a-zA-Z0-9_]', ''
    }

    # Extract rows and data cells
    $roles = [System.Collections.ArrayList]::new()
    $rowMatches = [regex]::Matches($tableHtml, "<tr.*?>(.*?)</tr>", "IgnoreCase, Singleline")

    # Skip the header row (first row)
    foreach ($rowMatch in $rowMatches | Select-Object -Skip 1) {
        $rowData = [ordered]@{}
        $cellMatches = [regex]::Matches($rowMatch.Groups[1].Value, "<td.*?>(.*?)</td>", "IgnoreCase, Singleline")

        if ($cellMatches.Count -ge $headers.Count) {
            for ($i = 0; $i -lt $headers.Count; $i++) {
                # Extract text, removing any HTML tags
                $cellContent = [regex]::Replace($cellMatches[$i].Groups[1].Value, "<.*?>", "").Trim()
                
                # Decode HTML entities
                try {
                    Add-Type -AssemblyName System.Web -ErrorAction SilentlyContinue
                    $cellContent = [System.Web.HttpUtility]::HtmlDecode($cellContent)
                } 
                catch {
                    Write-Verbose "HTML decoding unavailable. Content may contain HTML entities."
                }
                
                $rowData[$headers[$i]] = $cellContent
            }
            [void]$roles.Add([PSCustomObject]$rowData)
        }
    }

    Write-Verbose "Successfully extracted $($roles.Count) Entra roles."
    return $roles
}
$entraRoles = Get-EntraRolesFromWeb

Then to obtain a list of valid role names, I just need to store the name column into a list, for later reference.

$validRoleNames = $entraRoles | Select-Object -ExpandProperty Role -Unique

Now that I have compiled my collection of Microsoft Graph API permissions and Microsoft Entra roles, I can craft a message to send to Gemini, hoping for a meaningful and accurate response. Here’s what I came up with:

Based on only the built in Microsoft Entra roles on this page: https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference, what is the least privilege role for the following Microsoft Graph API permission: $permission. Provide only the Role Name as a response and only provide a role that is in the list of roles here $validRoleNames, but use the data on the webpage to determine which roles is the least privileged role. Do not provide any other information or context. Just the role name.

Notice that I have included guardrails in my message to Gemini, prompting it to make a logical decision based on a collection of valid roles.

Now that we have constructed our prompt and added some guardrails, we can use the following two cmdlets provided by Doug to send our message to Gemini:

  • New-ChatMessage: The New-ChatMessage function builds a chat message object based on the prompt. The chat message object is used to send a prompt to the AI model for completion.
  • Invoke-ChatCompletion: The Invoke-ChatCompletion function sends a prompt to a specified AI model provider and returns the completion response.
Note: While the latest version of Gemini (albeit rate-limited) provided a concise and clear response, the general availability version added some trailing whitespace that I needed to trim. Doug has also included examples in the GitHub repository on how to loop messages to multiple LLMs, enabling you to choose your preferred LLM based on their responses.

In the example below, $permission represents one object in the $DelegatedAdminPermissions array.

$message = New-ChatMessage -Prompt "Based on only the built in Microsoft Entra role on this page: https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference, what is the least privilege role for the following Microsoft Graph API permission: $permission. Provide only the Role Name as a response and only provide a role that is in the list of roles here $validRoleNames, but use the data on the webpage to determine which roles is the least privileged role. Do not provide any other information or context. Just the role name."
$result = Invoke-ChatCompletion -Message $message -TextOnly -ErrorAction Stop
$result = $result.Trim()

Looping through multiple AI queries

As my original goal was to map all Microsoft Graph API delegated permissions to the least privilege built-in Microsoft Entra Role, I need to loop through and process each permission, then add the results of each message as a member property of the current item in the loop. 

To achieve this, I have written this small code block which will loop through each permission in the Graph API permissions list and query Gemini for a response.

Foreach ($permission in $DelegatedAdminPermissions) {
        Write-Host "Processing permission: $($permission.value)..."
        $message = New-ChatMessage -Prompt "Based on only the built in Microsoft Entra role on this page: https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference, what is the least privilege role for the following Microsoft Graph API permission: $permission. Provide only the Role Name as a response and only provide a role that is in the list of roles here $validRoleNames, but use the data on the webpage to determine which roles is the least privileged role. Do not provide any other information or context. Just the role name."
        try {
            $result = Invoke-ChatCompletion -Message $message -TextOnly -ErrorAction Stop
            $result = $result.Trim()   
            if ($validRoleNames -contains $result) {
                Write-Host "  Found valid role: $result"
                $permission | Add-Member -MemberType NoteProperty -Name "LeastPrivilegeRole" -Value $result -Force
            } else {
                Write-Warning "Role '$result' returned by AI is not found in the official Entra roles list. Setting empty."  
                $permission | Add-Member -MemberType NoteProperty -Name "LeastPrivilegeRole" -Value "" -Force 
            }
        } catch {
            Write-Error "  Failed to get role for permission $($permission.value): $_"
            $permission | Add-Member -MemberType NoteProperty -Name "LeastPrivilegeRole" -Value "" -Force
        }
        Start-Sleep -Seconds 3
}

The output of this is a full list of Graph API delegated permissions, mapped to the least privileged Entra role. A visual table and csv list has been uploaded to the following GitHub Repo.

Wrapping up

AI isn’t perfect, however I believe I chose the best LLM to produce the most accurate result as a first pass. But remember, Microsoft haven’t made an official role mapping available to the public, but behind the scenes, there are obvious components within the Microsoft service which explicitly define which Graph API permissions should be available to call based on the Entra role or a specific action a role enables.

Remember, this is a community effort, I have created a first pass at this, which is now publicly available on GitHub, I encourage you to submit a PR if you find something that is not accurate.

Daniel Bradley

Daniel Bradley is a UK-based technical architect and Microsoft MVP in Security. He specialises in Microsoft Entra, Intune, and Microsoft Graph PowerShell and is the author of Microsoft Graph PowerShell for Administrators. He writes and edits Our Cloud Network using experience gained from working with Microsoft cloud environments.

Leave a Reply