Advertisement
Yevrag35

Custom 'Connect-AzureAD'

Jul 22nd, 2019
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function Login-AzureAD()
  2. {
  3.     [CmdletBinding(PositionalBinding=$false)]
  4.     param
  5.     (
  6.         [parameter(Mandatory=$false)]
  7.         [guid] $TenantId = $tenId,
  8.  
  9.         [parameter(Mandatory=$false)]
  10.         [guid] $ClientId = $cliid,
  11.  
  12.         [parameter(Mandatory=$false)]
  13.         [string] $RedirectUri = $redUri
  14.     )
  15.  
  16.     $url = "https://login.microsoftonline.com/{0}/oauth2/token" -f $TenantId
  17.     $aadRes = 'https://graph.windows.net/'
  18.     $grphRes = 'https://graph.microsoft.com/'
  19.  
  20.     $path = Resolve-Path -Path "$env:ProgramFiles\WindowsPowerShell\Modules\AzureAD*" -ErrorAction Stop
  21.     $dll = Get-ChildItem -Path $path -Include Microsoft.IdentityModel.Clients.ActiveDirectory.dll -Recurse
  22.     if (@($dll).Count -ne 1)
  23.     {
  24.         throw "Couldn't find the proper ActiveDirectory.dll!"
  25.     }
  26.     else
  27.     {
  28.         Import-Module $dll.PSPath -ErrorAction Stop -Global
  29.     }
  30.  
  31.     $platform = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters(
  32.         [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Auto
  33.     )
  34.  
  35.     $ErrorActionPreference = "Stop";
  36.     $authContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($url, $true)
  37.     $task = $authContext.AcquireTokenAsync($aadRes, $ClientId, $RedirectUri, $platform)
  38.     $task.Wait()
  39.  
  40.     if ($task.Status -ne "RanToCompletion")
  41.     {
  42.         return
  43.     }
  44.     $aadToken = $task.Result.AccessToken
  45.     $userId = $task.Result.UserInfo.UniqueId
  46.     $graphTask = $authContext.AcquireTokenSilentAsync($grphRes, $ClientId)
  47.     $graphTask.Wait()
  48.     if ($graphTask.Status -ne "RanToCompletion")
  49.     {
  50.         return
  51.     }
  52.     $graphToken = $graphTask.Result.AccessToken
  53.     $graphToken | Set-Clipboard
  54.    
  55.     $manifest = Get-ChildItem -Path $dll.PSParentPath *.psd1 -File
  56.     Import-Module $manifest.PSPath -ErrorAction Stop -Global
  57.  
  58.     Connect-AzureAD -TenantId $TenantId -AccountId $userId -AadAccessToken $aadToken -MsAccessToken $graphToken
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement