In this post, lets have a look at how we can authenticate to the Microsoft Graph REST API through PowerShell. There are a few examples already available online but either they refer to old endpoints or they present the user with a login prompt to enter a username and password before authentication.
A few other examples ask for a client id to be submitted with the authentication request. You can get this client id when you register a new app in Azure AD. But what if you don't want to create an app registration? You already have a username and password, so creating a new Azure AD application just for authentication seems redundant.
Fortunately, there is way to authenticate to the Microsoft Graph API without any login prompts and without the need to create an explicit Azure AD application.
To avoid using any login prompts, we will use the AuthenticationContext.AquireToken method from the Active Directory Authentication Library (ADAL).
To avoid creating a new Client Id and Azure AD application, we will use a well know Client Id reserved for PowerShell: 1950a258-227b-4e31-a9cf-717495945fc2 This is a hard coded GUID known to Azure AD already.
Here are the steps we are going to do:
1) Make sure we have the username and password of a user in Azure AD
2) Use the username, password and PowerShell client id to get an access token from ADAL.
2) Use the access token to call the Microsoft Graph REST API.
Before going ahead, make sure you have the Microsoft.IdentityModel.Clients.ActiveDirectory.dll on your machine. If you have been working with Office 365/Azure PowerShell, chances are you have this already. If not, you can get it from a number of places. You can use the Azure Resource Manager PowerShell cmdlets to get a hold of it: https://docs.microsoft.com/en-us/powershell/azure/install-azurerm-ps?view=azurermps-4.0.0 or you can use nuget to download it: https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory
And here is the PowerShell script to authenticate the Microsoft Graph:
Running this script gets the current user from the /v1.0/me endpoint:
Thanks for reading!
Nice post. As I hate plumbing I use the PnP commandlet Connect-PnPMicrosoftGraph instead. It does not have ADAL support just yet, until they work out how to include my suggested PR or refactor the cmdlets :)
Yup looks like you need to create an App Registration in Azure AD and get a ClientId and ClientSecret before you can use the Connect-PnPMicrosoftGraph cmdlet.
The current cmdlet only support MSAL apps - but that works just fine. Then you can get the token using Get-PnPAccessToken and use that in subsequent REST queries.
Post a Comment