Using Azure AD Device Code Flow with PowerShell

Azure AD supports OAuth 2.0 Device Flow for Browserless and Input Constraint devices, as described here;

Assuming you do not want to, or cannot, use ADAL in PowerShell, you can script this flow entirely in native PowerShell.

$clientId = "1950a258-227b-4e31-a9cf-717495945fc2"       # This is the standard Client Identifier for Windows Azure PowerShell
$redirectUrl = [System.Uri]"urn:ietf:wg:oauth:2.0:oob"   # This is the standard Redirect URI for Windows Azure PowerShell
$tenant = ""
$resource = "";
$serviceRootURL = "$tenant"
$authUrl = "$tenant";

$postParams = @{resource="$resource";client_id="$clientId"}
$response = Invoke-RestMethod -Method POST -Uri "$authurl/oauth2/devicecode" -Body $postParams
Write-Host $response.message

$tokenParams = @{grant_type="device_code"; resource="$resource"; client_id="$clientId"; code="$($response.device_code)"}

$tokenResponse = $null
$maxDate = (Get-Date).AddSeconds($response.expires_in)

while (!$tokenResponse -and (Get-Date) -lt $maxDate)
        $tokenResponse = Invoke-RestMethod -Method POST -Uri "$authurl/oauth2/token" -Body $tokenParams
    catch [System.Net.WebException] 
        if ($_.Exception.Response -eq $null)

        $result = $_.Exception.Response.GetResponseStream()
        $reader = New-Object System.IO.StreamReader($result)
        $reader.BaseStream.Position = 0
        $errBody = ConvertFrom-Json $reader.ReadToEnd();

        if($errBody.Error -ne "authorization_pending")

        Write-Host -NoNewline ".";

After executing this script, and after successfully authenticating against Azure AD, the variable $tokenResponse should contain your tokens as issued by Azure AD.

Comments (0)

Skip to main content