Skip to content

Instantly share code, notes, and snippets.

@darrenjrobinson
Last active December 1, 2018 22:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darrenjrobinson/1010b622f84052fa471bc7a140aa390b to your computer and use it in GitHub Desktop.
Save darrenjrobinson/1010b622f84052fa471bc7a140aa390b to your computer and use it in GitHub Desktop.
PowerShell to Micrsoft Graph API Authentication. Associated blog post can be found here https://blog.darrenjrobinson.com/adding-removing-user-office365-licences-using-powershell-and-the-azure-ad-graph-restapi/
# the default path to where the ADAL GraphAPI PS Module puts the Libs
# Adding the AD library to your PowerShell Session.
Add-Type -Path 'C:\Program Files\WindowsPowerShell\Modules\AzureADPreview\1.1.143.0\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
# This is the tenant id of you Azure AD. You can use tenant name instead if you want.
$tenantID = "my.o365tenant.com"
$authString = "https://login.microsoftonline.com/$tenantID"
# Here, the username must be MFA disabled user Admin at least, and must not be a live id.
$username = "admin@my.o365tenant.com"
$password = 'P@$$w0rd!0!'
# The resource URI for your token.
$resource = "https://graph.windows.net/"
# This is the common client id.
$client_id = "1950a258-227b-4e31-a9cf-717495945fc2"
# Create a client credential with the above common client id, username and password.
$creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" `
-ArgumentList $username,$password
# Create a authentication context with the above authentication string.
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" `
-ArgumentList $authString
# Acquire access token from server.
$authenticationResult = $authContext.AcquireToken($resource,$client_id,$creds)
# Use the access token to setup headers for your http request.
$authHeader = $authenticationResult.AccessTokenType + " " + $authenticationResult.AccessToken
$headers = @{"Authorization"=$authHeader; "Content-Type"="application/json"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment