Pages

Sunday, April 21, 2024

Access Microsoft Graph with access token via PowerShell


Create and Register new Azure AD Application


Go to Azure Portal > Azure Active Directory > App Registration > New Application Registration


















Register application with below configurations
  • Name: <Application Name>
  • Supported Account Types: Accounts in this organizational directory only (mycloudpro only - Single tenant)
  • Redirect URI(Optional): <keep this blank>

Click Register 


























Go to Owners > Add owners > Add the necessary user as a owner of the application
















Go to Certificates & Secrets > Client Secrets > New client secret 
  • Description: <Name>
  • Expires: <Expiration period, EX: 2 years>

Click Add














Note: Make a note of Secret ID and Value. Please note that the complete value is not showing you again after leave the page. Therefore Do Not Forget to make a note of secret value. You paste it to notepad and save in secure location.

Go to API permissions > Add permission > Microsoft Graph > Add below permissions to the newly registered application.

Note: You can choose the required permissions as your requirement. 

Click Grant admin consent for the tenant
















Make a not of Tenant ID, Client ID and Secret value of the application. Because there are going to use in the PowerShell script.


Create  a PowerShell script for Auth Token

#################################
#Script Start

$TenantId ="23xxxxx-xxx-xxx-xxx-xxxxxx1"
$ClientId ="33xxxxxx-xxxx-xxxx-xxxx-xxxxxxxx4"
$Secret = "c2xxx~xxxxxxxxxxxxxxxxxxxxxxxxxxxxxED"


$uri = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"

$content = "application/x-www-form-urlencoded"

$queryURI = 'https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/439aaf2e-f738-46c3-a177-4aaff4475a01/?$expand=categories,assignments'


$body = @{

    grant_type = "Client_credentials"
    client_id = $ClientId
    client_secret = $Secret
    scope = "https://graph.microsoft.com/.default"
    

}

#Send a post request to obtain bearer token 

$response = Invoke-WebRequest -Method Post -Uri $uri -Body $body -ContentType $content -UseBasicParsing -ErrorAction Stop

#$accessToken = $response.access_token | ConvertTo-SecureString -AsPlainText -Force

$atoken = ($response.Content | ConvertFrom-Json).access_token

#Generate Header for query by adding Access Token obtained earlier 

$queryHeaders = @{ 
   
    Authorization = "Bearer $atoken"


#Send request  

$queryResult = (Invoke-RestMethod -Method Get -Headers $queryHeaders -Uri $queryURI)

#$queryResult.value

write-host $queryResult

#Script End
#################################


References: