Skip to content

Instantly share code, notes, and snippets.

@watahani
Created April 24, 2021 07:20
Show Gist options
  • Save watahani/f53468b819ab1e35bcc5f4d0d1cb3ee2 to your computer and use it in GitHub Desktop.
Save watahani/f53468b819ab1e35bcc5f4d0d1cb3ee2 to your computer and use it in GitHub Desktop.
$tenantId = "<tenant-id>"
$clientId = "<client-id>"
$body = @{
client_id=$clientId;
scope='openid profile'
}
$authZUrl ="https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/devicecode"
$authZRes = Invoke-RestMethod -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body -Uri $authZUrl;$authZRes
# user_code : GPCKQUN8T
# device_code : GAQABAAEAAAAGV_bv21oQQ4ROqh0_1-tA9qD2QclDyTMbZJfAz9_HxPrCU6VycmAx8B1loeNHYZYlw2xeDTv8BO46pumk_bxnQuT
# vlEmPhsz2ltg6n7_6aavwWRLByvpTUOB3M_tNBDIt61oQ_zS1rNgIQBepe3ZlItswkaEuPMFsVjg4FIoY3AIAXmW6xLWUlJ9U6dy
# ndzEgAA
# verification_uri : https://microsoft.com/devicelogin
# expires_in : 900
# interval : 5
# message : To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code
# GPCKQUN8T to authenticate.
$tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$body2 = @{
grant_type="urn:ietf:params:oauth:grant-type:device_code";
client_id=$clientId;
device_code=$authZRes.device_code;
}
while($true){
try {
$tokenRes= Invoke-RestMethod -Method POST -ContentType "application/x-www-form-urlencoded" -Body $body2 -Uri $tokenUrl
$tokenRes
break;
} catch {
$e = $_.ErrorDetails.Message | ConvertFrom-Json;
if($e.error -eq "authorization_pending"){
$e.error_description
Sleep $authZRes.interval
} else {
throw $_
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment