Skip to content

Instantly share code, notes, and snippets.

@azurekid
Last active December 19, 2022 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azurekid/b11fadf23471ac42e5d964580db90b14 to your computer and use it in GitHub Desktop.
Save azurekid/b11fadf23471ac42e5d964580db90b14 to your computer and use it in GitHub Desktop.
PowerShell function to create Graph Access Token
function Get-GraphToken {
[cmdletbinding()]
Param(
[Parameter(Mandatory = $True)]
[String[]]
[ValidateSet("MSGraph", "Azure", "Monitor", "MSPIM")]
$Client,
[Parameter(Mandatory = $False)]
[String]$Resource = "https://graph.microsoft.com"
)
switch ($Client) {
"MSGraph" {
$body = @{
"client_id" = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"resource" = "https://graph.microsoft.com/"
"scope" = "CrossTenantInformation.ReadBasic.All"
}
}
"Azure" {
$body = @{
"client_id" = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"resource" = "https://management.core.windows.net"
}
}
"Monitor" {
$body = @{
"client_id" = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"resource" = "https://monitor.azure.com/"
}
}
"MSPIM" {
$body = @{
"client_id" = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"resource" = "https://api.azrbac.mspim.azure.com"
}
}
}
# Login Process
$authResponse = Invoke-RestMethod `
-UseBasicParsing `
-Method Post `
-Uri "https://login.microsoftonline.com/common/oauth2/devicecode?api-version=1.0" `
-Body $body
Write-Output $authResponse.message
$continue = $true
$body = @{
"client_id" = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"grant_type" = "urn:ietf:params:oauth:grant-type:device_code"
"code" = $authResponse.device_code
}
while ($continue) {
Start-Sleep -Seconds $authResponse.interval
$total += $authResponse.interval
if ($total -gt ($authResponse.expires_in)) {
Write-Error "Timeout occurred"
return
}
try {
$global:graphToken = Invoke-RestMethod `
-UseBasicParsing `
-Method Post `
-Uri "https://login.microsoftonline.com/common/oauth2/token?api-version=1.0 " `
-Body $body `
-ErrorAction SilentlyContinue
}
catch {
$details = $_.ErrorDetails.Message | ConvertFrom-Json
$continue = $details.error -eq "authorization_pending"
Write-Output "Waiting for approval: $($continue)"
if (!$continue) {
Write-Error $details.error_description
return
}
}
if($graphToken) {
break
}
}
}
@azurekid
Copy link
Author

Added option to request access token for MS-PIM endpoint

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment