Connect to MS Graph API PowerShell SDK Using a Certificate

In this Microsoft Graph PowerShell SDK post, we will show you how to connect to the service from a Windows machine and authenticate using a certificate.

Microsoft Graph Powershell SDK offers multiple authentication methods for Microsoft 365. We need to use App Only authentication to connect to the Graph API service without an authentication prompt.

An App-Only authentication is handy when connecting and performing operations programmatically using PowerShell, C#, Python and other programming languages.

To connect to Microsoft 365 using a certificate, we must first create an App Registration in Entra ID and then create a certificate. Once your app registration is ready, assign it Application Permissions and continue to the next step.

Create a Certificate

Use the PowerShell code to create a self-signed certificate on a Windows machine.

The following code will create a certificate and export it in a .CER format to the path (FilePath) in the export-certificate command.

$certname = "MSGraphTest-tenant"
$cert = New-SelfSignedCertificate -Subject "CN=$certname" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256

Export-Certificate -Cert $cert -FilePath "C:\Users\USERNAME\Documents\$certname.cer"  

Load Certificate to App Registration

Before we connect, we need to load the certificate to an App Registration. Open the App Registration from the Entra portal.

Click on Certificates & secrets.

Click on Certificates

Click on Upload certificate

Upload the .CER file (from the Create a Certificate section)

Note the name of the certificate under Description.

It is time to connect to Microsoft 365 using the Graph PowerShell SDK.

Connect to Graph PowerShell SDK

To connect to the Graph API service, first install the PowerShell module

Install-Module -Name Microsoft.Graph -force -AllowClobber

Use the following cmdlet using the application ID of the app registration, your tenant ID and the certificate’s name.

Connect-MgGraph -ClientId "clientid" -TenantId "tenantid" -CertificateName "CN=MSGraphTest-tenant"


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.