GitHub Icon Image

Authenticate with and call the Microsoft Graph

Summary

Obtain a new access token for the Microsoft Graph and use it an HTTP request, or connect to the Graph to perform operations.

Example Screenshot

Scripts

  • CLI for Microsoft 365 using PowerShell
  • CLI for Microsoft 365 using Bash
  • PnP PowerShell
  • Microsoft Graph PowerShell

$token = m365 util accesstoken get --resource https://graph.microsoft.com --new
$me = Invoke-RestMethod -Uri https://graph.microsoft.com/v1.0/me -Headers @{"Authorization"="Bearer $token"}
$me

Check out the CLI for Microsoft 365 to learn more at: https://aka.ms/cli-m365

#!/bin/bash

# requires jq: https://stedolan.github.io/jq/

token=`m365 util accesstoken get --resource https://graph.microsoft.com --new`
me=`curl https://graph.microsoft.com/v1.0/me -H "Authorization: Bearer $token"`
echo $me | jq

Check out the CLI for Microsoft 365 to learn more at: https://aka.ms/cli-m365

#https://docs.microsoft.com/en-us/powershell/module/sharepoint-pnp/connect-pnponline?view=sharepoint-ps#example-7
Connect-PnPOnline -Url "https://contoso.sharepoint.com" -ClientId 6c5c98c7-e05a-4a0f-bcfa-0cfc65aa1f28 -Tenant 'contoso.onmicrosoft.com' -Thumbprint 34CFAA860E5FB8C44335A38A097C1E41EEA206AA

$token = Get-PnPGraphAccessToken
$uri = 'https://graph.microsoft.com/v1.0/users?$filter=displayName eq ''Paul Bullock'''
$me = Invoke-RestMethod -Uri $uri -Headers @{"Authorization"="Bearer $($token)"} -Method Get -ContentType "application/json"
$me.value

Check out the PnP PowerShell to learn more at: https://aka.ms/pnp/powershell


Connect-MgGraph
Get-MgContext
Get-MgUser -Filter "displayName eq 'Paul Bullock'"
Disconnect-MgGraph

Check out the Microsoft Graph PowerShell SDK to learn more at: https://docs.microsoft.com/en-us/graph/powershell/get-started

Source Credit

Sample first appeared on https://pnp.github.io/cli-microsoft365/sample-scripts/graph/call-graph/

Contributors

Author(s)
Garry Trinder
Paul Bullock

Disclaimer

THESE SAMPLES ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

Back to top Script Samples
Generated by DocFX with Material UI