Skip to content

Instantly share code, notes, and snippets.

Embed
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\2.0.0.98\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
# Azure tenant
$tenant = "customer.com.au"
# Application ID for Powershell client
$client_Id = "1950a258-227b-4e31-a9cf-717495945fc2"
# Login URI
$authority = "https://login.microsoftonline.com/$tenant"
#redirect uri of powershell
[uri]$redirectUri = "urn:ietf:wg:oauth:2.0:oob"
# API URL
$resource = 'https://graph.windows.net/'
# Username and Password
$username = "user1@customer.com.au"
$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 = "https://graph.windows.net/{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.