PowerShell Function to Get Azure AD Token

When making Azure Resource Manager REST API calls, you will firstly need to obtain an Azure AD authorization token and use it to construct the authorization header for your HTTP requests.

My good friend Stanislav Zhelyazkov (@StanZhelyazkov) has written a PowerShell function call Get-AADToken as part of the OMSSearch PowerShell module for this purpose. You can find it in the OMSSearch project’s GitHub repo: https://github.com/slavizh/OMSSearch/blob/master/OMSSearch.psm1

I have been using this functions in many projects in the past and it served me well. However, the limitation for Stan’s function is that it only works with user principals – you can only generate such a token if you have an USER account. Today, I needed to make ARM REST API calls using an Azure AD application Service Principal. So I had to update Stan’s function in order to support AAD applications. Here’s the updated version:

By default, if you don’t specify the ‘AuthenticationType’, it defaults to ‘UserPrincipal’ and everything works just like before. But to generate AAD token for an Azure AD application, you will need to use the AAD Application Id (as user Id) and AAD Application password  (as password) to construct a pscredential object, then specify ‘ServicePrincipal’ as the ‘AuthenticationType’ parameter value.

Here are two examples how to use both UPN and SPN in a REST call to get all resource groups in your Azure subscription:

Using User Principals:

Using AAD Application Service Principals:

The HTTP request returns a response that’s saved in the $GetResourceGroupsRequest variable. To access the result, you will need to convert the response content from JSON to PSobject. i.e.

image

Leave a Reply

%d bloggers like this: