Skip to content

Instantly share code, notes, and snippets.

@sonphnt
Forked from vman/MSGraphPowerShellAuth.ps1
Created September 13, 2017 06:11
Show Gist options
  • Save sonphnt/ae94c3355567707f0b65b4112c70351b to your computer and use it in GitHub Desktop.
Save sonphnt/ae94c3355567707f0b65b4112c70351b to your computer and use it in GitHub Desktop.
#I am using the Azure Resource Manager cmdlets to get hold of the dll. https://docs.microsoft.com/en-us/powershell/azure/install-azurerm-ps?view=azurermps-4.0.0
Add-Type -Path "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.ApiManagement\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$azuretenantADName = "yourtenant.onmicrosoft.com"
$userName = "user1@yourtenant.onmicrosoft.com"
$userPassword = "password" #Using plain text password for demo purpose.
#Authority to Azure AD Tenant
$AzureADAuthority = "https://login.microsoftonline.com/$azuretenantADName/oauth2/v2.0/authorize"
#Resource URI to the Microsoft Graph
$resourceURL = "https://graph.microsoft.com/"
#PowerShell Client Id. This is a well known client id used by PowerShell and known to Azure AD. You don't need to create an Azure AD app with this id.
$powerShellClientId = "1950a258-227b-4e31-a9cf-717495945fc2"
# Create UserCredential object
$userCreds = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential($userName, $userPassword)
# Create AuthenticationContext
$authContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($AzureADAuthority)
# Acquire token to the Microsoft Graph using the PowerShell client id and user credentials.
$authResult = $authContext.AcquireToken($resourceURL, $powerShellClientId, $userCreds)
$authHeader = $authResult.CreateAuthorizationHeader()
$requestHeader = @{
"Authorization" = $authHeader
"Content-Type" = "application/json"
}
#REST call to get the current user. (i.e. the user from the $userCreds object)
$Uri = "https://graph.microsoft.com/v1.0/me"
#Get data from the beta endpoint: Get all Azure AD applications
#Uri = "https://graph.microsoft.com/beta/applications"
$Result = (Invoke-RestMethod -Method Get -Headers $requestheader -Uri $Uri)
if($Result.value){ $Result.value } else { $Result }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment