Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# The resource URI
$resource = ""
# Your Client ID and Client Secret obainted when registering your WebApp
$clientid = "726ec7c7-ff9e-4c28-b864-************"
$clientSecret = "KjYwt9tIf13kdBub7vaBJv4********************="
$redirectUri = "https://localhost:8001"
# UrlEncode the ClientID and ClientSecret and URL's for special characters
$clientIDEncoded = [System.Web.HttpUtility]::UrlEncode($clientid)
$clientSecretEncoded = [System.Web.HttpUtility]::UrlEncode($clientSecret)
$redirectUriEncoded = [System.Web.HttpUtility]::UrlEncode($redirectUri)
$resourceEncoded = [System.Web.HttpUtility]::UrlEncode($resource)
$scopeEncoded = [System.Web.HttpUtility]::UrlEncode("")
# Function to popup Auth Dialog Windows Form
Function Get-AuthCode {
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object -TypeName System.Windows.Forms.Form -Property @{Width=440;Height=640}
$web = New-Object -TypeName System.Windows.Forms.WebBrowser -Property @{Width=420;Height=600;Url=($url -f ($Scope -join "%20")) }
$DocComp = {
$Global:uri = $web.Url.AbsoluteUri
if ($Global:uri -match "error=[^&]*|code=[^&]*") {$form.Close() }
$web.ScriptErrorsSuppressed = $true
$form.ShowDialog() | Out-Null
$queryOutput = [System.Web.HttpUtility]::ParseQueryString($web.Url.Query)
$output = @{}
foreach($key in $queryOutput.Keys){
$output["$key"] = $queryOutput[$key]
# Get AuthCode
$url = "$redirectUriEncoded&client_id=$clientID&resource=$resourceEncoded&prompt=admin_consent&scope=$scopeEncoded"
# Extract Access token from the returned URI
$regex = '(?<=code=)(.*)(?=&)'
$authCode = ($uri | Select-string -pattern $regex).Matches[0].Value
Write-output "Received an authCode, $authCode"

This comment has been minimized.

Copy link

@Nilis312 Nilis312 commented Jun 13, 2017

Hi Darren,

I got the error message:
Unable to find type [System.Web.HttpUtility].

  • $queryOutput = [System.Web.HttpUtility]::ParseQueryString($web.Ur ...
  •                ~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : InvalidOperation: (System.Web.HttpUtility:TypeName) [], RuntimeException
    • FullyQualifiedErrorId : TypeNotFound

After adding "Add-Type -AssemblyName System.Web" at the beginning of the PowerShell script is started to work.
Running Windows 10 Creators update + .net 4.7.


This comment has been minimized.

Copy link

@RLolico RLolico commented Apr 23, 2019

I use localhost:8000 as my app adress in azure,
Got error AADSTS90102: 'redirect_uri' value must be a valid absolute Uri.
Any ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.