Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
AuthN to AzureAD using PowerShell and AzureAD PSM ADAL Helper Lib
# ADAL Helper Lib
Add-Type -Path 'C:\Program Files\WindowsPowerShell\Modules\AzureAD\\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
# Azure tenant
$tenant = ""
# Application ID for Powershell client
$client_Id = "1950a258-227b-4e31-a9cf-717495945fc2"
# Login URI
$authority = "$tenant"
#redirect uri of powershell
[uri]$redirectUri = "urn:ietf:wg:oauth:2.0:oob"
$resource = ''
# Username and Password
$username = ""
$password = ConvertTo-SecureString "myP@$sw0rd" –asplaintext –force
$credentials = New-Object System.Management.Automation.PSCredential $Username,$password
# Endpoint
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
# Credentials to connect
$AADcredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential" -ArgumentList $credentials.UserName,$credentials.Password
# AuthN and get token
$authenticationResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext,$resource,$client_Id,$AADcredential).result
# create AuthN Header
$AuthHeader = $authenticationResult.CreateAuthorizationHeader()
# URI to get first 999 users
$url = "{0}/users?`$top=999&api-version=1.6"
# Get a batch of 999 users
$users = Invoke-RestMethod -Method Get -Headers @{
Authorization = $authenticationResult.CreateAuthorizationHeader()
'Content-Type' = "application/json"
} -Uri ($url -f $authenticationResult.TenantId)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.