Connect To Graph API Using PowerShell With Delegated Permissions

Previously on this blog, I have posted some Graph API / PowerShell examples. Most of these examples so far have used application permissions. I have a few examples planned over the next week or so which leverage Delegated Permissions which have a different authentication flow which we need to keep in mind when writing our scripts.

To start, Delegated Permissions run on behalf of a user account, where Application Permissions do not need a user account. The drawback to Application Permissions is that not all endpoints support manipulation using Application Permissions.

In this post, I will go through two methods of retrieving an Access Token using Delegated Permissions.

Registering the Application

Registering the application in Azure AD works the exact same as when we are using Application Permissions. In the Azure AD Portal, open the Application Registrations blade and create a new Registration.

Give the registration a name and configure the Redirect URI, as we are running scripts against this, set this to “https://localhost” – more on this later.

With the registration created, we now need to give it permissions, navigate to the API Permissions blade and add in your required delegated permissions. When done, ensure to grant consent as we would with application permissions.

Next, create a secret under the “Certificates & Secrets” blade and save it for later, make sure to copy when it appears as you only get one chance to copy it.

On the “Overview” page, take note of the “Application” and “Directory” IDs and we can move on to our scripts.

Using an Authorization Code

To generate an authorization code, we can navigate to the following URL syntax:

https://login.microsoftonline.com/<Tenant ID>/oauth2/v2.0/authorize?client_id=<Application ID>&response_type=code&redirect_uri=<Redirect URI specified>&response_mode=query&scope=offline_access%20<Scopes separated by "%20">&state=12345"

for example, let’s take the following parameters:

  • Application ID: 00000000-0000-0000-0000-000000000000
  • Directory ID: 11111111-1111-1111-1111-111111111111
  • Scopes: Group.Read.All
  • Redirect URI: https://localhost

This URL would look like:

https://login.microsoftonline.com/11111111-1111-1111-1111-111111111111/oauth2/v2.0/authorize?client_id=00000000-0000-0000-0000-000000000000&response_type=code&redirect_uri=https%3A%2F%2Flocalhost&response_mode=query&scope=offline_access%20group.read.all&state=12345"

Navigating to this URL will redirect you to your Redirect URL, in our case “https://localhost&#8221;. The URL will look like the below:

https://localhost/?code=0.AAAA6oYdB2gy7EKs1Wyc9PfaFm1kOCGXYMFFluTD8Hul2EFuAKM.AQABAAIAAAB2UyzwtQEKR7-rWbgdcBZIB7uadIWW7ZbXgT-tiSEWPfzNedky3tV0qh4iglRXvHw1ufwhX-xhpUSFAgzJZJU2N27W5X2tPCE30h68jCHeCK_6BtuTcvK7Jjx3OWf0nOw94zJdaozTDqvu8FEkkyVCjYykf0AZFB2HsSpvAoX0k94xteUcnCevHEgFwVqFFBtn5a0OVsqVuZ5gjr4MPjONB_eiurqJdri5GAjy0FdJrtkoKSNp94UFr_UETbqZxayl0sVuHWHAiUl4GYzvP3LylVvv85VInCWlHRqVgiQiNTgGDt7DYGIm_0s5VWKVzNC6Bmnig111h5FKv1hzohyWjrCZNn9o07XV7GaHgrR59wIDUDk0s7VgpITdOcNJ7XBHd3sNR5LRCe5HohgyLUmGxOu9mRQc3WQdDH3xZDKAjEns6NOvejv6BKoxuEA4pMjcbyZx7E4STSq70sJdVjJ2nTjpi9iFeDyADqk5SSJBu93_iE8mpS5uglb1EFIYDx0AmJJ6_j2bmpox0dudNkGqDS5jxMIF-15hqwdDQwjr1zxw6NTMsVijrApTYe0wdsGOJudP1IOvy9yCsXjFmyOakNoJK177jsaLQh_9fYqllLPZLUUdHL8GQnbjDCMp66AgAA&state=12345%22&session_state=4244f0a0-8f07-4842-bb90-4adf8fbf4058#

Copy the Code value from the URL you are redirected to, we will use this to request our token. Now create the following variables in your PowerShell Session:

  • $ClientID – Set this to the Application ID from the App Reg
  • $DirectoryID – Set this to the Directory (tenant) ID
  • $ClientSecret – Set this to the secret value copied earlier
  • $Code – Set this to the code from the previous step

Finally, with each of these variables set, we can issue the token request with the below code:

    $ReqTokenBody = @{
        Grant_Type    = "authorization_code"
        client_Id     = $clientID
        code          = $code
        redirect_uri  = "https://localhost"
        client_secret = $clientsecret


    } 

    $Tokenresult = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantID/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody

Now our $TokenResult variable holds our access token, in the below screenshot you can see the layout of the $TokenResult variable, the access_token value is the on we will use in our Graph calls.

Using the MSAL.PS Module

The MSAL.PS Module makes the process of requesting an Access Token much easier that the above method. The first thing to do, is install the module. This can be done using the below command:

Install-Module -Name MSAL.PS 

Ensure to check the latest version here.

Once installed, we need to declare our variables as in the previous method, declare the following variables:

  • $ClientID – Set this to the Application ID from the App Reg
  • $DirectoryID – Set this to the Directory (tenant) ID
  • $Code – Set this to the code from the previous step

Now we can simply run the below command to request a token:

$Token = Get-MsalToken -DeviceCode -ClientId $clientID -TenantId $tenantID -RedirectUri $RedirectURI

In the PowerShell window, you’ll see a message similar to the below:

Navigate to the URL https://Microsoft.com/devicelogin and enter the code when prompted. Log in as your admin user and you’ll be prompted to close the browser window and continue in PowerShell.

Now we have an access token in our $Token variable. Here’s a screenshot of what it will look like, the token itself is held in the AccessToken attribute:

And that’s it, two different methods for getting an access token via PowerShell. I will reference this post in future posts where we will use this access token to leverage Graph API for various functions.

2 thoughts on “Connect To Graph API Using PowerShell With Delegated Permissions

  1. Pingback: Export Microsoft Planner Instances and Details Using Graph API and PowerShell – Admin Sean Mc

  2. Pingback: Use Graph API and PowerShell to Add SecureScore Entries to Planner – Sean McAvinue

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s