Using Azure AD Managed Service Identity to Access Microsoft Graph with Azure Functions and PowerShell
Recently Microsoft released an exciting new preview in Azure AD: Managed Service Identity! You can go and read the details at the Enterprise Mobility + Security blog, and some examples of usage scenarios: https://azure.microsoft.com/en-us/blog/keep-credentials-out-of-code-introducing-azure-ad-managed-service-identity/ Managed Service Identity makes it possible to keep credentials out of code, and that is a very inviting prospect. As I have been exploring Microsoft Graph in different scenarios using PowerShell, I thought I should have a go at using Managed Service Identity in an Azure Function and run some PowerShell commands to get data from the Microsoft Graph. Lets get started!
Configuring the Azure Function
First, if you haven’t already created an existing Azure Function App, go ahead and do that. Here is my Function App I will use in this demo:







Permissions and Roles for the Managed Service Identity
Depending of what you want to do with your Function App, the managed service identity, represented by the service principal, will need some permissions to access resources. You could give the service principal rights to Azure resources like Virtual Machines, or to access Key Vault secrets (a nice blog post on that here: https://blog.kloud.com.au/2017/09/19/enabling-and-using-managed-service-identity-to-access-an-azure-key-vault-with-azure-powershell-functions/
).
In my scenario I want to access the Microsoft Graph, and specifically get some Directory data like user information from my Azure AD. When accessing Microsoft Graph you would normally register an Azure AD Application and set up Application or Delegated Permissions, and follow the authentication flow for that. But in this case I want the Service Principal to be able to directly access Directory Data, so I will have to give my Service Principal permission to do that.
The following Azure AD commands adds my service principal to the AD Directory Role “Directory Readers”:


Creating a PowerShell Function for the Managed Service Identity
In your Function App, you can now create a new Function, selecting language PowerShell, and in this case I will create it as a HttpTrigger Function:







Querying the Microsoft Graph
With a valid Access Token, and with the correct permissions for the resources I will want to access, I can now run some Microsoft Graph API queries.
In my example I have some test users in my tenant named after the popular Seinfeld show. In fact I have set a “Seinfeld” department attribute value on those. So my query for getting those users would be:
https://graph.microsoft.com/v1.0/users?$filter=Department
eq ‘Seinfeld’
A great way to test Microsoft Graph Commands is to use the Graph Explorer, https://developer.microsoft.com/en-us/graph/graph-explorer
, and if you sign in to your own tenant you can query your own data. As an example, I have showed that here:



