Thursday, 21 December 2017

Connect Microsoft Graph API using PnP PowerShell

In this article I will show you how to connect Microsoft Graph and query user details using SharePoint PnP PowerShell Online module.

Prerequisites:

Before proceed we need to download and install the latest PnP PowerShell module. You can download latest released setup from GitHub. If your main OS is Windows 10, and if you have PowerShellGet installed, you can run the following command to install the PnP PowerShell module instead of download and install the setup:
Install-Module SharePointPnPPowerShellOnline -SkipPublisherCheck -AllowClobber -Force

Connect PnPOnline and Get Access Token:

To connect and query Microsoft Graph api end-point, first we need to get the access token with required permissions using Connect-PnPOnline and Get-PnPAccessToken cmdlets.
Connect-PnPOnline -Scopes "User.Read","User.ReadBasic.All"
$accessToken =Get-PnPAccessToken
You can refer Microsoft Grap Documentation to know more about required permissions for every end-point url.

Connect and Get data from Microsoft Graph Api :

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

Example 1: The below command get the current user profile details.
$apiUrl = "https://graph.microsoft.com/v1.0/me"
$myPrfoile = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get
Example 2: The below command get all the Azure AD user details.
$apiUrl = "https://graph.microsoft.com/v1.0/users"
$users = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get
Note: You can also refer this document Microsoft Graph Api Permissions to know more about Delegated permissions and Application permissions (Admin Consent).

Advertisements
Advertisements

No comments:

Post a Comment