Search code examples
azurepowershellazure-active-directoryazure-functionsmicrosoft-graph-sdks

Azure Function - Powershell - Graph SDK - Get users/Groups


I'm trying to get some users information via Azure function using graph SDK. While I'm able to connect and print out the context every time I try to use users or groups cmdlets I get ERROR: Object reference not set to an instance of an object error.

Can anyone help with this?

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)


$appid = 'eaf7a235'
$tenantid = '723058'
$secret = '~SomeCode'
 
$body =  @{
    Grant_Type    = "client_credentials"
    Scope         = "https://graph.microsoft.com/.default"
    Client_Id     = $appid
    Client_Secret = $secret
}
 
$connection = Invoke-RestMethod `
    -Uri https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token `
    -Method POST `
    -Body $body
 
$token = $connection.access_token  | ConvertTo-SecureString -AsPlainText -Force
 

Connect-MgGraph -AccessToken $token

$user = Get-MgUser -UserId 'someone@here.com' | convertto-json -depth 100 ##here the function crash


Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = [HttpStatusCode]::OK
    Body = $user
})

I've tried the same with get group commandlet. Tried same code in a powershell window and it work.


Solution

  • Don't try to serialize a MicrosoftGraphUser, it will create an infinite loop and your function will run out of memory:

    graph is a piece of shit

    Use Invoke-MgGraphRequest instead with -OutputType Json:

    $user = Invoke-MgGraphRequest GET 'v1.0/users/someone@here.com' -OutputType Json
    

    Or reduce the serialization -Depth.


    As aside, please don't hardcode your secret in your function's body, use a Key Vault instead. Furthermore, you can use your function's Managed Identity if you have it enabled:

    Connect-AzAccount -Identity
    $token = Get-AzAccessToken -ResourceTypeName MSGraph
    Connect-MgGraph -AccessToken (ConvertTo-SecureString $token.Token -AsPlainText)
    

    NOTE: Add Az.Accounts in your requirements.psd1 or place the module in the function's Modules folder for Connect-AzAccount.