Friday, 5 January 2018

Connect to Microsoft Graph API using PowerShell

In this article I will explain how to connect to Microsoft Graph and query current user information from Azure AD. To call Microsoft Graph, we must first acquire an access token from Azure Active Directory (Azure AD), we can get access token either using registered Azure AD application or by using well known Azure AD clients (Ex: PowerShell).


We are going to get access token by using AuthenticationContext.AquireToken method from the Active Directory Authentication Library (ADAL). To use ADAL library we need to install Azure Resource Manager PowerShell. If your main OS is Windows 10, and if you have PowerShellGet installed, you can run the following command to install the Azure Resource Manager PowerShell module.
Install-Module AzureRM -SkipPublisherCheck -AllowClobber -Force

Function - GetAccessToken

Instead of creating a new Client Id and Azure AD application, here we are using a well know Client Id reserved for PowerShell: 1950a258-227b-4e31-a9cf-717495945fc2.
Function GetAccessToken
    param (        
        [Parameter(Position=0, Mandatory=$false)] 
        [string] $Office365Username, 
        [Parameter(Position=1, Mandatory=$false)] 
        [string] $Office365Password
    # Add ADAL (Microsoft.IdentityModel.Clients.ActiveDirectory.dll) assembly path from Azure Resource Manager SDK location
    Add-Type -Path "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
    # or simply import AzureRm module using below command
    # Import-Module AzureRm
    #PowerShell Client Id. This is a well known Azure AD client id of PowerShell client. You don't need to create an Azure AD app.
    $clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
    $redirectUri = "urn:ietf:wg:oauth:2.0:oob"
    $resourceURI = ""
    $authority = ""
    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
    if (([string]::IsNullOrEmpty($Office365Username) -eq $false) -and ([string]::IsNullOrEmpty($Office365Password) -eq $false)) 
    $SecurePassword = ConvertTo-SecureString -AsPlainText $Office365Password -Force            
    #Build Azure AD credentials object  
    $AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $Office365Username,$SecurePassword
    # Get token without login prompts.
    $authResult = $authContext.AcquireToken($resourceURI, $clientId,$AADCredential)
    # Get token by prompting login window.
    $authResult = $authContext.AcquireToken($resourceURI, $clientId, $redirectUri, [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Always)
    return $authResult.AccessToken

Connect and Fetch data from Azure AD using Rest API :

Once you get the required access token you can easily query graph api using Invoke-RestMethod cmdlet by passing access token.

Get Access Token : The below command gets required access token with login prompts.
$accessToken= GetAccessToken
Get Access Token by passing credentials without login prompts:
$accessToken= GetAccessToken -Office365Username "" -Office365Password "admin_pwd"
Example 1: The below command gets the current user profile details.
$apiUrl = ""
$myPrfoile = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get
Example 2: The below command gets all the Azure AD user details.
$apiUrl = ""
$users = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get


No comments:

Post a Comment