The OAuth 2.0 Password Grant Type allows authentication (in this case to Graph) using a username and password.
Take note of the Resource Identifier used with REST queries as this changes based on te resources being accessed.
<#
Script Purpose: To demonstrate connecting to Graph API with the
Password Grant Type
#>
$TenantID = "myaccount.onmicrosoft.com"
$AccountName = "testuser@myaccount.onmicrosoft.com"
$Password = "SecretPassword"
$ClientId = "1950a258-227b-4e31-a9cf-717495945fc2" # Common Tenant Id
# Constants - Endpoints
$AzureResourceURI = "https://login.microsoftonline.com/$($tenantID)/oauth2/token"
$ResourceID = "https://graph.microsoft.com"
# Construct the Body for the POST
$Body = "grant_type=password"`
+"&username=" +$Accountname `
+"&client_id=" +$clientId `
+"&password=" +$Password `
+"&resource=" +[system.uri]::EscapeDataString($ResourceID)
# The result should contain a token for use with Graph
$Response = Invoke-WebRequest -Uri $AzureResourceURI -Method POST -Body $Body
$ResponseJSON = $Response|ConvertFrom-Json
#Add the token to headers for the Graph request
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("Authorization", "Bearer "+$ResponseJSON.access_token)
$Headers.Add("Content-Type", "application/json")
#Two different Graph endpoints are available - uncomment when required
$Uri = "https://graph.microsoft.com/beta/"
#$Uri = "https://graph.microsoft.com/v1.0/"
# Call Graph
$Request = Invoke-RestMethod -Uri $Uri -Headers $Headers -Method Get -ContentType "application/json"
write-output $Request.Value
- Log in to post comments