Created
December 12, 2018 21:18
-
-
Save ThePVD/bcf7df2fcb603d23dfb1b6d2a34b1912 to your computer and use it in GitHub Desktop.
Azure Powershell device login (utilize SSO when credentials are not known)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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 = "tenantid.onmicrosoft.com" # Substitute tenant ID here | |
$resource = "https://management.azure.com"; | |
$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 | |
add-AzureRmAccount -accountid $tokenresponse.id_token -AccessToken $tokenresponse.access_token | |
} | |
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 "."; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment