Connect to Microsoft Graph PowerShell Using an App Registration

April 20, 2022
5 min read
Syndicated

Connecting to the Microsoft Graph using PowerShell is simple and easy. The most straightforward approach is to pass the required scopes as part of the “Connect-MgGraph“; however, this means you may have to consent each time, and most will constantly if you adjust the scopes.

Initial Connection

$scopes = @(
	"Chat.ReadWrite.All"
	"Directory.Read.All"
	"Group.Read.All"
)

Connect-MgGraph -Scopes $scopes

Get-MgContext | Select-Object -ExpandProperty Scopes

Updated Connection

$scopes = @(
	"Chat.ReadWrite.All"
	"Directory.Read.All"
	"Group.Read.All"
	"Mail.ReadWrite"
	"People.Read.All"
	"Sites.Manage.All"
	"User.Read.All"
	"User.ReadWrite.All"
)

Connect-MgGraph -Scopes $scopes

Get-MgContext | Select-Object -ExpandProperty Scopes

Though helpful, this approach may not be the best when you need to execute these types of commands more frequently. To help us, we can utilize a pre-created App Registration with the correctly assigned permissions to connect.

There are a few steps required for this to work.

  • Create the App Registration
  • Assign the required Graph Permissions
  • Upload a Certificate

Create the App Registration

Assign the required Graph Permissions

Now we have the App Registration, click to access the details. Within the Manage navigation, click “API Permissions.”

  • Click “Add a permission
  • Click “Microsoft Graph
  • Click “Application permissions
  • Select the required permissions

For this example, we will use the following:

  • Chat.ReadWrite.All
  • Directory.Read.All
  • Group.Read.All
  • Mail.ReadWrite
  • People.Read.All
  • Sites.Manage.All
  • User.Read.All
  • User.ReadWrite.All

Click “Add permissions

The selected permissions will display on the “API Permissions” page.

For those permissions that require “Admin Consent,” click the “Grant admin consent for {Domain}.”

Upload a Certificate

Within the Manage navigation, now click “Certificates & secrets.”

NOTE: You need a certificate for this. If you do not have a fully purchased certificate, you can generate a self-signed certificate. More details are here: https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-self-signed-certificate.

  • Click “Upload certificates
  • Browse locally for your certificate
  • Click “Add

We now have all the pieces required to connect to the Microsoft Graph using the App Registration. You need to copy the following values to use:

  • App Registration ID
  • Azure Active Directory Tenant ID
  • Certificate Thumbprint or Name

Once you have these values, you can use the following PowerShell to connect:

Connect-MgGraph `
	-ClientId "2f5ab44a-b61a-448e-a47e-ad5f3ad519ff" `
	-TenantId "9c7659c3-acfa-42e7-b56a-ebc98f327ec6" `
	-CertificateThumbprint "6E442BCB760DEE68D59746CE7D7457EF7EAB33C3"

If the connection is successful, you can execute the following to validate an “App Only” connection, and the “Scopes” are populated. If they are empty, you incorrectly assigned the graph permissions as delegated, not as application.

Get-MgContext

To view just the scopes you can use this command.

Get-MgContext | Select-Object -ExpandProperty Scopes

In our “App registration,” we did not add the “SecurityEvents.ReadWrite.All” graph permission, so any command requiring that should fail.

Get-MgSecurityAlert

We can reissue the command if we go back to the “App registration” and add the required permission.

If you execute the “Get-MgSecurityAlert” command, it will fail as the connection scopes do not reflect this change. You need to reconnect and then issue the command for it to work.

Disconnect-MgGraph

Connect-MgGraph `
	-ClientId "2f5ab44a-b61a-448e-a47e-ad5f3ad519ff" `
	-TenantId "9c7659c3-acfa-42e7-b56a-ebc98f327ec6" `
	-CertificateThumbprint "6E442BCB760DEE68D59746CE7D7457EF7EAB33C3"

Get-MgSecurityAlert
Get-MgSecuritySecureScore

This approach is a perfect way of securely connecting to the Graph, especially if you need to control the allowed scopes.

What About if You Don’t Want To Use a Certificate?

What is you don’t want to utilize a certificate and would instead like to use the client secret approach with an access token? Well that was a conversation that Drew Madelung (@dmadelung) and myself were having so I decided to post it here.

# Populate with the App Registration details and Tenant ID
$appid = ''
$tenantid = ''
$secret = ''

$body =  @{
	Grant_Type    = "client_credentials"
	Scope         = "https://graph.microsoft.com/.default"
	Client_Id     = $appid
	Client_Secret = $secret
}

$connection = Invoke-RestMethod `
	-Uri https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token `
	-Method POST `
	-Body $body

$token = $connection.access_token

Connect-MgGraph -AccessToken $token
Liam Cleary

Liam Cleary

Liam began his career as a computer trainer. He quickly realized that programming, breaking and hacking were much more fun. Liam spent the next few years working within core infrastructure and security services. He is now the founder and owner of SharePlicity, a consulting company focusing on Microsoft 365 and Azure technology. His role within SharePlicity is to help organizations implement Microsoft 365 and Azure technology to enhance internal and external collaboration, document, and records management, automate business processes, and implement security controls and protection. He is a long-time Microsoft MVP and Microsoft Certified Trainer, focusing on architecture, security and crossing the boundary into software development. Over the past few years, his specialty has been security in Microsoft 365, Azure and its surrounding platforms. Liam also creates online training courses for Pluralsight, LinkedIn Learning and Cloud Academy, and he teaches multiple Microsoft certification courses for Opsgility and Microsoft. You can find him at user groups and conferences, teaching classes, offering advice, spending time in the community, teaching his kids how to code, raspberry PI programming, hacking the planet, building Lego robots, or coaching soccer. You may also find him running races in the dark, hiking, or mountain biking at breakneck speeds.