I saw similar questions being asked many times, but still couldn't make it work.
My test code :
$azureAplicationId ='ZZZZZZZZZZZZZZ'
$passwd="XXXXXXXXXXXXXXXXXXX"
$azureTenantId= 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
$azurePassword = ConvertTo-SecureString $passwd -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
$graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.microsoft.com").AccessToken
$aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken
Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id -MsAccessToken $graphToken
$Headers = @{
'Authorization' = "Bearer $graphToken"
}
Invoke-WebRequest -H $Headers "https://graph.microsoft.com/v1.0/users" ### working as expected
Invoke-WebRequest -H $Headers "https://graph.microsoft.com/v1.0/devices" ### working as expected
Get-AzADUser #### working as expected
Get-AzureADUser #### not working
Get-AzureADDevice #### not working
Get-AzureADDevice shows :
Get-AzureADDevice : Error occurred while executing GetDevices
Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation.
I am trying to use a Azure app to read Azure AD device. Pity new Az module only provide Get-AzADUser, no Get-AzADDevice, so I have to use Get-AzureADDevice, but I just can't get it work.
I have tried AADToken and MSToken, and I have tested the MSToken with Invoke-WebRequest and it's working fine.
But when I run get-AzureADDevice or any GetAzureAD command, it just gave me the error Insufficient privileges to complete the operation.
Get-AzADuser or GetAzADApplication are working fine. I have granted the app all the permission I can think of: