Build PowerShell scripts with Microsoft Graph and app-only authentication
This tutorial teaches you how to build a PowerShell script that uses the Microsoft Graph API to access data using app-only authentication. App-only authentication is a good choice for background services or applications that need to access data for all users in an organization.
Note
To learn how to use Microsoft Graph to access data on behalf of a user, see this user (delegated) authentication tutorial.
In this tutorial, you will:
Tip
As an alternative to following this tutorial, you can download or clone the GitHub repository and follow the instructions in the README to register an application and configure the project.
Prerequisites
Before you start this tutorial, you should have PowerShell installed on your development machine. PowerShell 5.1 is the minimum requirement, but PowerShell 7 is recommended.
You should also have a Microsoft work or school account with the Global administrator role. If you don't have a Microsoft 365 tenant, you might qualify for one through the Microsoft 365 Developer Program; for details, see the FAQ. Alternatively, you can sign up for a 1-month free trial or purchase a Microsoft 365 plan.
Note
This tutorial was written with PowerShell 7.2.2 and Microsoft Graph PowerShell SDK version 1.9.5. The steps in this guide may work with other versions, but that has not been tested.
Register the app in the portal
In this exercise you will register a new application in Microsoft Entra to enable app-only authentication.
Create a self-signed certificate
The Microsoft Graph PowerShell SDK requires a certificate for app-only authentication. For development purposes, a self-signed certificate is sufficient. You need a certificate with the private key installed on the local machine, and the public key exported in a .CER, .PEM, or .CRT file.
On Windows, you can use the pki PowerShell module to generate the certificate.
$cert = New-SelfSignedCertificate -Subject "CN=PowerShell App-Only" -CertStoreLocation `
"Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 `
-KeyAlgorithm RSA -HashAlgorithm SHA256
Export-Certificate -Cert $cert -FilePath "./PowerShellAppOnly.cer"
Register application for app-only authentication
In this section you will register an application that will support app-only authentication using client credentials flow.
Open a browser and navigate to the Microsoft Entra admin center and login using a Global administrator account.
Select Microsoft Entra ID in the left-hand navigation, expand Identity, expand Applications, then select App registrations.
Select New registration. Enter a name for your application, for example,
Graph App-Only Auth Tutorial
.Set Supported account types to Accounts in this organizational directory only.
Leave Redirect URI empty.
Select Register. On the application's Overview page, copy the value of the Application (client) ID and Directory (tenant) ID and save them, you will need these values in the next step.
Select API permissions under Manage.
Remove the default User.Read permission under Configured permissions by selecting the ellipses (...) in its row and selecting Remove permission.
Select Add a permission, then Microsoft Graph.
Select Application permissions.
Select User.Read.All, then select Add permissions.
Select Grant admin consent for..., then select Yes to provide admin consent for the selected permission.
Select Certificates and secrets under Manage, then select Certificates.
Select Upload certificate. Upload the PowerShellAppOnly.cer or powershell.crt file you created in the previous step, then select Add.
Note
Notice that, unlike the steps when registering for user authentication, in this section you did configure Microsoft Graph permissions on the app registration. This is because app-only auth uses the client credentials flow, which requires that permissions be configured on the app registration. See The .default scope for details.
Add app-only authentication
In this section you will use app-only authentication with the Microsoft Graph PowerShell SDK.
Connect with app-only authentication
Disconnect any existing Microsoft Graph connection using the following command.
Disconnect-MgGraph
Open PowerShell and use the following command to set the
$clientID
session variable, replacing <your-client-id> with the client ID of your app registration.$clientId = <your-client-id>
Set the
$tenantId
session variable, replacing <your-tenant-id> with your organization's tenant ID.$tenantId = <your-tenant-id>
Set the
$certificate
session variable to the subject of the certificate created in the previous step.$certificate = "CN=PowerShell App-Only"
Use the
Connect-MgGraph
command to authenticate using the certificate from the previous step.Connect-MgGraph -ClientId $clientId -TenantId $tenantId -CertificateName $certificate
Use
Get-MgContext
to verify that you are authenticated with app-only authentication. Verify that AuthType isAppOnly
.PS > Get-MgContext ClientId : 2fb1652f-a9a0-4db9-b220-b224b8d9d38b TenantId : 601faea3-be45-4960-898f-92b379b17cd9 CertificateThumbprint : Scopes : {User.Read.All} AuthType : AppOnly AuthProviderType : ClientCredentialProvider CertificateName : CN=PowerShell App-Only Account : AppName : PowerShell Graph Tutorial ContextScope : Process Certificate : PSHostVersion : 2022.4.1 ClientTimeout : 00:05:00
List users
In this section you will list all users in your Azure Active Directory using app-only authentication.
In your authenticated PowerShell session, run the following command to list users.
Get-MgUser -Select "displayName,id,mail" -Top 25 -OrderBy "displayName"
Review the output.
Id DisplayName Mail UserPrincipalName UserType -- ----------- ---- ----------------- -------- 05fb57bf-2653-4396-846d-2f210a91d9cf Adele Vance AdeleV@contoso.com a36fe267-a437-4d24-b39e-7344774d606c Alex Wilber AlexW@contoso.com 54cebbaa-2c56-47ec-b878-c8ff309746b0 Allan Deyoung AllanD@contoso.com 9cb2ad7c-8e69-46a6-a947-a02c255048de Automate Bot 9a7dcbd0-72f0-48a9-a9fa-03cd46641d49 Bianca Pisani a8989e40-be57-4c2e-bf0b-7cdc471e9cc4 Brian Johnson (TAILSPIN) BrianJ@contoso.com 9e2d4937-44ee-4af4-bd56-77a12cc3ecc4 Cameron White 8990227d-31dc-4120-a38e-f652576974f4 Christie Cline ChristieC@contoso.com ...
Code explained
Consider the command used to list users.
- It uses
-Select
to request specific properties - It uses
-Top
to limit the number of users returned - It uses
-OrderBy
to sort the response
Optional: add your own code
In this section you will use your own Microsoft Graph PowerShell SDK commands. This could be a code snippet from Microsoft Graph documentation or Graph Explorer, or code that you created. This section is optional.
Choose an API
Find an API in Microsoft Graph you'd like to try. For example, the List groups API. You can use one of the examples in the API documentation, customize an API request in Graph Explorer and use the generated snippet, or use the Find-MgGraphCommand
command to find the corresponding command.
For example, the API endpoint to list groups is GET /groups
. You can use this to find the corresponding PowerShell command.
PS > Find-MgGraphCommand -Uri "/groups" -Method "GET"
APIVersion: v1.0
Command Module Method URI OutputType Permissions
------- ------ ------ --- ---------- -----------
Get-MgGroup Groups GET /groups IMicrosoftGraphGroup {Directory.Read.All, Directory.ReadWrite.All, Group.Read.All, G…
APIVersion: beta
Command Module Method URI OutputType Permissions
------- ------ ------ --- ---------- -----------
Get-MgGroup Groups GET /groups IMicrosoftGraphGroup1 {Directory.Read.All, Directory.ReadWrite.All, Group.Read.All, …
The output indicates that the Get-MgGroup
command is the corresponding command.
Configure permissions
Check the Permissions section of the reference documentation for your chosen API to see which authentication methods are supported. Some APIs don't support app-only, for example.
To call an API with app-only authentication (if the API supports it), add the required permission scope in the Azure AD admin center. Be sure to disconnect and reconnect using app-only permission.
Tip
Using the -ForceRefresh
parameter with the Connect-MgGraph
command ensures that newly configured permissions are applied.
Run the command
Now that you are connected with the required permissions, run your chosen command.
Congratulations!
You've completed the PowerShell Microsoft Graph app-only tutorial. Now that you have a working app that calls Microsoft Graph, you can experiment and add new features.
- Learn how to use user (delegated) authentication with the Microsoft Graph PowerShell SDK.
- Visit the Overview of Microsoft Graph to see all of the data you can access with Microsoft Graph.
Have an issue with this section? If so, please give us some feedback so we can improve this section.