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; https://tools.ietf.org/html/draft-ietf-oauth-device-flow-07

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 = "YOURTENANTNAME.onmicrosoft.com"
$resource = "https://graph.windows.net";
$serviceRootURL = "https://graph.windows.net/$tenant"
$authUrl = "https://login.microsoftonline.com/$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)
{
    try
    {
        $tokenResponse = Invoke-RestMethod -Method POST -Uri "$authurl/oauth2/token" -Body $tokenParams
    } 
    catch [System.Net.WebException] 
    {
        if ($_.Exception.Response -eq $null)
        {
            throw
        }

        $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")
        {
            throw
        }

        Start-Sleep($response.interval);
        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