Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get Tokens for accessing the Azure Reporting API. Associated Blog Post is located here
#Sample oAuth 2.0 Microsoft API Powershell AuthN/AuthZ Script
#The resource URI
$resource = ""
#Your Client ID and Client Secret obainted when registering your WebApp
$clientid = "802d26c7-363e-41c9-a64d-234567890"
$clientSecret = "tosVD1iasfdsadfsareXvTBNlQRRN/98765432345="
#Your Reply URL configured when registering your WebApp
$redirectUri = "https://localhost"
$scope = "Directory.Read"
Add-Type -AssemblyName System.Web
#UrlEncode the ClientID and ClientSecret and URL's for special characters
$clientIDEncoded = [System.Web.HttpUtility]::UrlEncode($clientid)
$clientSecretEncoded = [System.Web.HttpUtility]::UrlEncode($clientSecret)
$resourceEncoded = [System.Web.HttpUtility]::UrlEncode($resource)
$scopeEncoded = [System.Web.HttpUtility]::UrlEncode($scope)
#Refresh Token Path
$refreshtokenpath = "C:\temp\ReportingAPI\refresh.token"
# Function to popup Auth Dialog Windows Form for getting an AuthCode
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)
$Global:output = @{}
foreach($key in $queryOutput.Keys){
$output["$key"] = $queryOutput[$key]
function Get-AzureAuthN ($resource) {
# Get Permissions (if the first time, get an AuthCode and Get a Bearer and Refresh Token
# Get AuthCode
$url = "$redirectUri&client_id=$clientID&resource=$resourceEncoded&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"
#get Access Token
$body = "grant_type=authorization_code&redirect_uri=$redirectUri&client_id=$clientId&client_secret=$clientSecretEncoded&code=$authCode&resource=$resource"
$Authorization = Invoke-RestMethod `
-Method Post -ContentType "application/x-www-form-urlencoded" `
-Body $body `
-ErrorAction STOP
Write-output $Authorization.access_token
$Global:accesstoken = $Authorization.access_token
$Global:refreshtoken = $Authorization.refresh_token
if ($refreshtoken){$refreshtoken |out-file "$($refreshtokenpath)"}
if ($Authorization.token_type -eq "Bearer" ){
Write-Host "You've successfully authenticated to $($resource) with authorization for $($Authorization.scope)"
write-host "Check the console for errors. Chances are you provided the incorrect clientID and clientSecret combination for the API Endpoint selected"
function Get-NewTokens {
# We have a previous refresh token.
# use it to get a new token
$refreshtoken = Get-Content "$($refreshtokenpath)"
# Refresh the token
#get Access Token
$body = "grant_type=refresh_token&refresh_token=$refreshtoken&redirect_uri=$redirectUri&client_id=$clientId&client_secret=$clientSecretEncoded"
$Global:Authorization = Invoke-RestMethod `
-Method Post -ContentType "application/x-www-form-urlencoded" `
-Body $body `
-ErrorAction STOP
$Global:accesstoken = $Authorization.access_token
$Global:refreshtoken = $Authorization.refresh_token
if ($refreshtoken){
$refreshtoken | out-file "$($refreshtokenpath)"
write-host "Updated tokens"
$Global:headerParams = @{'Authorization'="$($Authorization.token_type) $($Authorization.access_token)"}
Get-AzureAuthN ($resource)
# Refresh our tokens
# Get-NewTokens
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment