Post

How to connect to Microsoft Graph API on macOS (and Windows)

With recent advancements in Apples CPU architecture (M1, M2) there was a need for a new way to connect to Microsofts Graph API on macOS, as the old modules were not compatible with the new architecture. Because there isn’t much info about this topic out there, this guide will show you how to connect to Microsoft Graph API on macOS using the new way. \

This guide is also applicable to Windows devices (just skip the powershell installation part).

And if you encountered this error while trying to connect with Connect-MsGraph: Could not load type 'System.Security.Cryptography.SHA256Cng' then this guide is for you as well.

Prerequisites

First you must have Powershell installed on your Mac. You can download it from the official website. The easiest way to install it is by using Homebrew:

1
brew install --cask powershell

To check if Powershell is installed correctly, run the following command:

1
pwsh

Connecting to Microsoft Graph API

Now let us connect to the Microsoft Graph API. First we need to install and import the required module:

Install-Module -Name Microsoft.Graph
Import-Module -Name Microsoft.Graph

There are a few ways to connect to Microsoft Graph API, but the easiest one is by using the Connect-MgGraph cmdlet. This cmdlet will open a browser window where you can login to your Microsoft account. You are now connected to the Microsoft Graph API!

Connect-MgGraph

You can also provide your tenant ID and client ID to the cmdlet, if you want to connect to a specific tenant or app:

Connect-MgGraph -TenantId <tenant-id> -ClientId <client-id>

By default, the cmdlet will use the https://graph.microsoft.com/.default scope. If you want to use a different scope, you can provide it to the cmdlet:

Connect-MgGraph -Scopes "DeviceManagementManagedDevices.Read.All"

Using a device code

Or if you can’t use a browser, you can use a device code to connect to the Microsoft Graph API. You can use it like this:

Connect-MgGraph -DeviceCode

This will print a device code and a URL to the console. Open the URL in a browser and enter the device code and authenticate with your credentials. You are now connected to the Microsoft Graph API!

Using the Microsoft Graph API

After you have connected to the Microsoft Graph API, you can start using it. For example, you can get all the user objects in your tenant:

$users = Get-MgUsers -All

foreach ($user in $users) {
    Write-Host $user.displayName
}

You should see a list of all the users in your tenant.