In a recent blog post I demonstrated how we can create an Azure AD App registration to configure a native application to control the access to corporate resources in Intune by associating permissions scopes. With that application configured, it’s time to take a look at how we can create a PowerShell function that for acquiring an access token using an Azure AD credential to access Intune Graph API.
Requirements
Before we dig into the PowerShell code, I assume that you have read my blog post about how to create the Azure AD App registration. See the link below:
Without the application setup properly, you’ll experience issues when attempting to run the authentication function provided in this post.
Authentication PowerShell function
For any PowerShell script that we want to write and access corporate resources through Intune Graph API, we need to authenticate with a valid identity. Acquiring the access token can be accomplished with various methods and below is a PowerShell function that I’ve built to make this process easier:
Simply just copy the code from the above link into any script that you’re writing for automating Intune tasks. At the beginning of your scripts, make sure that you invoke the function to get the access token that can be passed along as the header for Invoke-RestMethod cmdlet. An example of how the function can be used is shown below:
$AuthenticationHeader = Get-MSGraphAuthenticationToken -TenantName "emsmgmt.onmicrosoft.com" -ClientID "YOURGUIDHERE"
The function has two mandatory parameters that require input. TenantName should contain the your tenant name, e.g. tenant.onmicrosoft.com. ClientID should contain the application ID of your Azure AD App registration.
Code sample using the function
A more detailed example of how to use the function is shown below:
# Acquire access token $AuthenticationHeader = Get-MSGraphAuthenticationToken -TenantName "tenant.onmicrosoft.com" -ClientID "YOURGUIDHERE" # Get a list of applications $RESTResponse = Invoke-RestMethod -Method Get -Headers $AuthenticationHeader -Uri https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps if (-not[string]::IsNullOrEmpty($RESTResponse.Value)) { foreach ($Application in $RESTResponse.Value) { $Application.displayName } }
Add comment