Skip to content

Instantly share code, notes, and snippets.

@poiriersimon
Created September 21, 2018 17:36
Show Gist options
  • Save poiriersimon/9d970b460fc23bce40d6bbee827aad33 to your computer and use it in GitHub Desktop.
Save poiriersimon/9d970b460fc23bce40d6bbee827aad33 to your computer and use it in GitHub Desktop.
Sample Powershell script to connect and use Microsoft Graph API
#You need AzureAD Module (Save-Module AzureAD -Path C:\temp)
function GetAuthHeaders
{
[cmdletbinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Tenant = "",
[Parameter(Mandatory = $true)]
[string]$UserPrincipalName = ""
)
$ScriptDir = "C:\temp"
$AzureADModulePath = join-path $ScriptDir "\AzureAD"
$job = Start-Job -ArgumentList $AzureADModulePath ,$Tenant,$UserPrincipalName -ScriptBlock {
$AzureADModulePath = $args[0]
$Tenant = $args[1]
$UserPrincipalName = $args[2]
$adal = "$AzureADModulePath\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = "$AzureADModulePath\Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
$tMod = [System.Reflection.Assembly]::LoadFrom($adal)
$tMod = [System.Reflection.Assembly]::LoadFrom($adalforms)
[string] $clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
[string] $authority = "https://login.microsoftonline.com/$Tenant"
[uri] $redirectUri = "urn:ietf:wg:oauth:2.0:oob"
[string] $resourceURI = "https://graph.microsoft.com"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$PromptBehavior = [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Auto
$platformParam = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList $PromptBehavior
$userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList $UserPrincipalName, "OptionalDisplayableId"
$authResult = $authContext.AcquireTokenAsync($resourceUri, $clientId, $redirectUri, $platformParam, $userId)
$AuthHeader=$authResult.result.CreateAuthorizationHeader()
$headers = @{
"Authorization" = $AuthHeader
"Content-Type" = "application/json"
}
Return $headers
}
$Wait = Wait-Job $job
$jobResult = Receive-Job $job
Return $jobResult
}
$Tenant = "TENANTNAME.onmicrosoft.com"
$UserPrincipalName = "user@TENANTNAME.onmicrosoft.com"
$authheader = GetAuthHeaders -Tenant $Tenant -UserPrincipalName $UserPrincipalName
$uri ="https://graph.microsoft.com/v1.0/me/"
#$URI = "https://graph.microsoft.com/v1.0/reports/getMailboxUsageDetail(period='D7')"
$response = Invoke-RestMethod -Uri $uri -Headers $authHeader -Method Get
$response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment