If you're invoking this functionality from an Azure Function with a system-assigned managed identity, you can leverage this managed identity to authenticate with Microsoft Graph without needing to manage client secrets or other credentials directly within your code. You can use the managed identity to obtain an access token and then use that token to authenticate your requests to Microsoft Graph. Here's how you can modify the script to work with an Azure Function's managed identity:
Grant Necessary Permissions to the Managed Identity: Ensure that the system-assigned managed identity of your Azure Function has the necessary permissions (e.g., User.Read.All
or User.ReadBasic.All
) to read user properties from Azure AD through Microsoft Graph. You can assign these permissions in the Azure portal or using Azure CLI/PowerShell scripts.
Retrieve Access Token using Managed Identity: Modify the script to use the managed identity to obtain an access token. Azure Functions automatically provide an access token through its managed identity when running in Azure.
Here's how you can modify the script:
# Get access token using managed identity
$tokenEndpoint = $env:MSI_ENDPOINT + "?resource=https://graph.microsoft.com&api-version=2017-09-01"
$accessToken = Invoke-RestMethod -Method Get -Uri $tokenEndpoint -Headers @{"Secret"="$env:MSI_SECRET"} | Select-Object -ExpandProperty access_token
# Make a GET request to Microsoft Graph API
$userEndpoint = "https://graph.microsoft.com/v1.0/me"
$userResponse = Invoke-RestMethod -Uri $userEndpoint -Method Get -Headers @{Authorization = "Bearer $accessToken"} -ContentType "application/json"
# Get the description property from the response
$description = $userResponse.description
# Output the description
Write-Output "User Description: $description"
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin