Created
September 21, 2018 18:20
-
-
Save poiriersimon/743a4b6d9ccc9a7780970c1c25be0c53 to your computer and use it in GitHub Desktop.
Sample Function to catch expired Token in Powershell ADAL and do a new request.
This file contains 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
function TrapInvalidAuth { | |
Trap { | |
if($_ -like "*InvalidAuthenticationToken*"){ | |
$authheader = GetAuthHeaders;Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get | |
} | |
} | |
Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get | |
} | |
function GetAuthHeaders | |
{ | |
[cmdletbinding()] | |
param( | |
[Parameter(Mandatory = $true)] | |
[string]$Tenant = "", | |
[Parameter(Mandatory = $true)] | |
[string]$UserPrincipalName = "" | |
) | |
#$ScriptFullPath = $SCRIPT:MyInvocation.MyCommand.Definition | |
#$ScriptDir = Split-Path $ScriptFullPath -Parent | |
$ScriptDir = "C:\Temp" | |
$AzureADModulePath = join-path $ScriptDir "\AzureAD" | |
$job = Start-Job -ArgumentList $AzureADModulePath ,$Tenant,$UserPrincipalName -ScriptBlock { | |
$AzureADModulePath = $args[0] | |
$Tenant = $args[1] | |
$UserPrincipalName = $args[2] | |
$adal = "$AzureADModulePath\Microsoft.IdentityModel.Clients.ActiveDirectory.dll" | |
$adalforms = "$AzureADModulePath\Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll" | |
$tMod = [System.Reflection.Assembly]::LoadFrom($adal) | |
$tMod = [System.Reflection.Assembly]::LoadFrom($adalforms) | |
[string] $clientId = "1950a258-227b-4e31-a9cf-717495945fc2" | |
[string] $authority = "https://login.microsoftonline.com/$Tenant" | |
[uri] $redirectUri = "urn:ietf:wg:oauth:2.0:oob" | |
[string] $resourceURI = "https://graph.microsoft.com" | |
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority | |
$PromptBehavior = [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Auto | |
$platformParam = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters" -ArgumentList $PromptBehavior | |
$userId = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier" -ArgumentList $UserPrincipalName, "OptionalDisplayableId" | |
$authResult = $authContext.AcquireTokenAsync($resourceUri, $clientId, $redirectUri, $platformParam, $userId) | |
$AuthHeader=$authResult.result.CreateAuthorizationHeader() | |
$headers = @{ | |
"Authorization" = $AuthHeader | |
"Content-Type" = "application/json" | |
} | |
Return $headers | |
} | |
$Wait = Wait-Job $job | |
$jobResult = Receive-Job $job | |
Return $jobResult | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment