Skip to content

Instantly share code, notes, and snippets.

@watahani
Last active May 12, 2020 13:41
Show Gist options
  • Save watahani/c4fac41f339adb559262de1d33075521 to your computer and use it in GitHub Desktop.
Save watahani/c4fac41f339adb559262de1d33075521 to your computer and use it in GitHub Desktop.
sample script to grant access with authorize code flow and update token using refresh token
# Use it for debugging purpose only. DO NOT USE THIS SAMPLE for Production.
$clientId = 'cfc03012-2187-4644-8da4-1202c392cad1'
$clientSecret = 'client_secret'
$redirectUri='https://watahani.github.io/aad-playapp/'
$tenantId = "whdv.onmicrosoft.com"
$authorizeEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/authorize"
$tokenEndpont = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$scope = "openid https://graph.microsoft.com/.default offline_access"
$authparams = @{
client_id=$clientId;
redirect_uri=$redirectUri;
scope=$scope;
nonce="defaultNonce"
response_type="code"
prompt="login"
}
$authqueries = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
foreach($key in $authparams.Keys){
$authqueries[$key] = $authparams[$key]
}
$authUrl = $authorizeEndpoint + "?" + $authqueries.ToString()
$authUrl | clip.exe
Write-Host -ForegroundColor Yellow "Authorize Request URL cpied! Please past to browser and sign in!"
Write-Host "authUrl: $authUrl"
$code=Read-Host "Enter Authorize Code"
$postParams = @{
client_id = $clientId;
client_secret = $clientSecret;
redirect_uri=$redirectUri;
grant_type = 'authorization_code';
scope = $scope;
code=$code;
}
$body = (Invoke-WebRequest -Uri $tokenEndpont -Method POST -Body $postParams) | ConvertFrom-Json
$refreshToken=$body.refresh_token
Get-Date
$jwt = Decode-JWT $body.id_token
$jwt.claims
Write-Host "========================================"
$at = Decode-Jwt $body.access_token
$at.claims
Write-Host "========================================"
for($i=0; $i -lt 10; $i ++){
Sleep 30
$body = @{
client_id = $clientId;
client_secret = $clientSecret;
redirect_uri = $redirectUri;
grant_type= 'refresh_token';
refresh_token = $refreshToken;
}
$tokenResp = Invoke-WebRequest -Uri $tokenEndpont -Method POST -ContentType 'application/x-www-form-urlencoded'` -body $body;
$times += ((Get-Date) - $start).TotalMilliseconds
$body = ConvertFrom-Json $tokenResp.Content ;
Get-Date
$jwt = Decode-JWT $body.id_token
$jwt.claims
Write-Host "========================================"
$at = Decode-Jwt $body.access_token
$at.claims
Write-Host "========================================"
$refreshToken=$body.refresh_token
}
# https://gallery.technet.microsoft.com/JWT-Token-Decode-637cf001
function Convert-FromBase64StringWithNoPadding([string]$data)
{
$data = $data.Replace('-', '+').Replace('_', '/')
switch ($data.Length % 4)
{
0 { break }
2 { $data += '==' }
3 { $data += '=' }
default { throw New-Object ArgumentException('data') }
}
return [System.Convert]::FromBase64String($data)
}
function Decode-JWT([string]$rawToken)
{
$parts = $rawToken.Split('.');
$headers = [System.Text.Encoding]::UTF8.GetString((Convert-FromBase64StringWithNoPadding $parts[0]))
$claims = [System.Text.Encoding]::UTF8.GetString((Convert-FromBase64StringWithNoPadding $parts[1]))
$signature = (Convert-FromBase64StringWithNoPadding $parts[2])
$customObject = [PSCustomObject]@{
headers = ($headers | ConvertFrom-Json)
claims = ($claims | ConvertFrom-Json)
signature = $signature
}
Write-Verbose -Message ("JWT`r`n.headers: {0}`r`n.claims: {1}`r`n.signature: {2}`r`n" -f $headers,$claims,[System.BitConverter]::ToString($signature))
return $customObject
}
function Get-JwtTokenData
{
[CmdletBinding()]
Param
(
# Param1 help description
[Parameter(Mandatory=$true)]
[string] $Token,
[switch] $Recurse
)
if ($Recurse)
{
$decoded = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Token))
Write-Host("Token") -ForegroundColor Green
Write-Host($decoded)
$DecodedJwt = Decode-JWT -rawToken $decoded
}
else
{
$DecodedJwt = Decode-JWT -rawToken $Token
}
Write-Host("Token Values") -ForegroundColor Green
Write-Host ($DecodedJwt | Select headers,claims | ConvertTo-Json)
return $DecodedJwt
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment