Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save darrenjrobinson/57baa6191f3b32240c7349a4f03be63d to your computer and use it in GitHub Desktop.
Save darrenjrobinson/57baa6191f3b32240c7349a4f03be63d to your computer and use it in GitHub Desktop.
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