Last active
May 2, 2019 16:41
-
-
Save poiriersimon/ded7cdca600ba0aab84b75b7f47c1235 to your computer and use it in GitHub Desktop.
Powershell Function to Get Auth Header based on UPN with Graph API
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
#You need AzureAD Module (Save-Module AzureAD -Path C:\temp) | |
#Azure DLL are sideloaded in a job to bypass potential conflict with other version | |
function Get-GraphAuthHeaderBasedOnUPN | |
{ | |
[cmdletbinding()] | |
param( | |
[Parameter(Mandatory = $True)] | |
[string]$Tenant = "", | |
[Parameter(Mandatory = $false)] | |
[string]$clientId = "1950a258-227b-4e31-a9cf-717495945fc2", | |
[Parameter(Mandatory = $false)] | |
[string]$redirectUri = "urn:ietf:wg:oauth:2.0:oob", | |
[Parameter(Mandatory = $false)] | |
[string]$resourceAppIdURI = "https://graph.microsoft.com", | |
[Parameter(Mandatory = $false)] | |
[string]$AzureADPowershellModuleDir = "C:\Temp\AzureAD", | |
[Parameter(Mandatory = $True)] | |
[string]$UserPrincipalName = "" | |
) | |
#Requis de faire une job pour éviter les conflits de DLL avec EXO ADAL | |
$job = Start-Job -ArgumentList $Tenant,$UserPrincipalName,$AzureADPowershellModuleDir,$clientId,$redirectUri,$resourceAppIdURI -ScriptBlock { | |
$Tenant = $args[0] | |
$UserPrincipalName = $args[1] | |
$AzureADPowershellModuleDir = $args[2] | |
$clientId = $args[3] | |
$redirectUri = $args[4] | |
$resourceAppIdURI = $args[5] | |
$adal = "$($AzureADPowershellModuleDir)\Microsoft.IdentityModel.Clients.ActiveDirectory.dll" | |
$tMod = [System.Reflection.Assembly]::LoadFrom($adal) | |
[string] $authority = "https://login.microsoftonline.com/$Tenant" | |
$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($resourceAppIdURI, $clientId, $redirectUri, $platformParam, $userId) | |
$AuthHeader=$authResult.result.CreateAuthorizationHeader() | |
$headers = @{ | |
"Authorization" = $AuthHeader | |
"Content-Type" = "application/json" | |
"ExpiresOn" = $authResult.Result.ExpiresOn | |
} | |
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