Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

How to Connect to Graph PowerShell with a Client Secret

October 20, 2023
in Blog, Microsoft Graph, Powershell
0
ADVERTISEMENT

Table of Contents

After you install the Microsoft Graph module, you can connect to Microsoft Graph PowerShell. There are different methods to connect to Microsoft Graph PowerShell. In this article, we will show you how to connect to Microsoft Graph with client secret.

Install Microsoft Graph PowerShell module

1️⃣ First, you need to install the Microsoft Graph PowerShell module. We recommend you update to the latest version, because some of the cmdlets will not work.

Note Note: You need to install Microsoft Graph PowerShell module v2.x to connect with Microsoft Graph to run automated scripts.

2️⃣ Or you can open Windows PowerShell as administrator then run all below commands at once to download and install all required packages and modules.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force
Install-PackageProvider -Name NuGet -Force
Install-Module PowerShellGet -Force
Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted
Install-Module Microsoft.Graph -Force
Install-Module Microsoft.Graph.Beta -Force

3️⃣ Once done, you can verify you have installed the Microsoft Graph PowerShell module and see which version is running using the below PowerShell cmdlet.

PS C:\> Get-InstalledModule Microsoft.Graph | ft -AutoSize

Version Name            Repository Description
------- ----            ---------- -----------
2.4.0   Microsoft.Graph PSGallery  Microsoft Graph PowerShell module

After you installed the Microsoft Graph PowerShell module, you can start to connect.

Connect MgGraph with Client Secret app

Before we can connect to Microsoft Graph with PowerShell, you need to:

  • Register an application in Entra ID and assign API permissions.
  • Then create a client secret to the application for authentication without sign in.

Register new application in Entra ID

First, you need to register an application, where you will get the Application (client) ID and Directory (tenant) ID. Register a new application in Microsoft Entra admin center:

1️⃣ Sign into Microsoft Entra admin center > Identity > Applications > App registrations > New registration.

9UaxOZCEfibAXwhY0esxzhY6sx1FswCdsSJeyVNqIJu6ydcSpmLWTIr8gq2m

2️⃣ Register an application.

  • Name your application as you want.
  • Select Accounts in this organizational directory only (- Single tenant)
  • Click Register
ZIiMU3miJfEup8JZL6oIbTQXLK7aPr4MRwCRgyyoDAFp9T6ttRs4orBOMxAM

3️⃣ Successfully created application, you will be redirected to the app overview page. Copy the Application ID and Directory ID.

gMUdOWUaKr9INpAfU49hzPBGElOD7Q4MYczuZIgSlLTbhtvRWm9PzgpuxtN2

You need to copy the below values and paste them into Notepad because you need them later when connecting to Microsoft Graph:

  • Application (client) ID: 3c17a3d6-8f7f-4407-b76f-ff0d22e4ab7a
  • Directory (tenant) ID: c032627b-6715-4e39-9990-bcf48ee5e0c5

Assign API permissions

You must assign API permissions to the application you created.

1️⃣ Click API permission > Click Add a permission.

FDhKHyuGRDdcsTbZvXC9HfMPUaJQftHrjdwUaWrHi4JavH6fy67AOGLXspOQ

2️⃣ Under the tab Microsoft APIs > Click Microsoft Graph

Mke4fsR67hQUxa83fCiTDiXHrOttKMepXhNS5PICaoLmWj4e1P9q3MSeTE5e

3️⃣ Click Application permissions > Search for User.Read.All > Select User > User.Read.All > Click Add permissions

7mp4lsWY3jpZLNVLuIdvabio88pUTrSo1qktS3NSHWDCX2WagEiq7WOYgqNU

4️⃣ Click Grant admin consent for your tenant > Click Yes

bDvSkFdcs77WOiPezBsGGxfwzkF3yXXaWn4aWazWW2Oc0OGCkVuF2oSLQWT1

A green check mark appears that you granted admin consent successfully!

AC6ZIygIjr7Avyk0C9qfsWGyocCCuWUa3RGx9oykTLDQP5vyrKWZPCNLS3lw

Create a client secret

1️⃣ To create a Client Secret for your application in Microsoft Entra portal, follow these steps:

  1. Click on Certificates & secrets
  2. Click Client secrets > New client secret
  3. Type the description
  4. Select an expiration date
  5. Click Add
CSKXeHxsDI6pRYX12HicbCrvYXhGmrqKN2D4LptYNrhX167abHY6r0Byu8H9

2️⃣ Copy the client secret Value and save it.

Note Note: Client secret values cannot be viewed except immediately after creation. Remember to save the secret when created before leaving the page.
kJh5plJoqIBOyr2HAWEYiywCKAYKe5DDdROMXR5z4FJrC7gwl8k659FjGYT2

3️⃣ Connect to Microsoft Graph with Client Secret. You need to change the below parameters values to connect to Microsoft Graph with Client Secret:

# Configuration
$ClientId = "4ca434dd-463e-4124-9c06-46c765ca67da"
$TenantId = "c032627b-6715-4e39-9990-bcf48ee5e0c5"
$ClientSecret = "jEk8Q~oChrP1J8xMXVuJ81T9st5W_~pgE308raZk"

# Convert the client secret to a secure string
$ClientSecretPass = ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force

# Create a credential object using the client ID and secure string
$ClientSecretCredential = New-Object `
    -TypeName System.Management.Automation.PSCredential `
    -ArgumentList $ClientId, $ClientSecretPass

# Connect to Microsoft Graph with Client Secret
Connect-MgGraph -TenantId $TenantId -ClientSecretCredential $ClientSecretCredential

That’s it! You successfully connected to Microsoft Graph PowerShell. You can get the details about the current connected session using Get-MgContext cmdlet.

PS C:\> Get-MgContext

ClientId               : 3c17a3d6-8f7f-4407-b76f-ff0d22e4ab7a
TenantId               : c032627b-6715-4e39-9990-bcf48ee5e0c5
Scopes                 : {User.Read.All}
AuthType               : AppOnly
TokenCredentialType    : ClientSecret
CertificateThumbprint  :
CertificateSubjectName :
Account                :
AppName                : myauth
ContextScope           : Process
Certificate            :
PSHostVersion          : 5.1.19041.3031
ManagedIdentityId      :
ClientSecret           : System.Security.SecureString
Environment            : Global

Assign more permissions to the app

$passwordProfile = @{Password = 'xWwvJ]6NMw+bWH-d'}
$params = @{
  "DisplayName"         = "Test10"
  "MailNickName"        = "Test10"
  "UserPrincipalName"   = "[email protected]"
}

New-MgUser @params -AccountEnabled -PasswordProfile $passwordProfile
PS C:\> Get-MgContext

Scopes                 : {User.Read.All}
...

In the previous session, we’ve assigned the Read-Only permission to the app. And then when you trying to create a new user, you should get the following error.

New-MgUser : Insufficient privileges to complete the operation.
Status: 403 (Forbidden)
ErrorCode: Authorization_RequestDenied
Date: 2023-09-13T12:42:48

This is good, because you just need to add enough permission to an app for specific actions. Anytime, you can add more permissions to the app when you need.

For example, to create a new user using Graph PowerShell. We need to add the scope Directory.ReadWrite.All to the app.

BcmLlpXRF9NI0qQMiYxU18iFV8fWZIhZpZA18P4LkzLDYxEtlAE40TWLJIrR

Don’t forget grant admin consent for your organization for the newly added permissions.

gvfSi3WZR7bUNYjxPggHX3KX3aZoN2IUdtoznmT0XLTCSkNxeK1bVKYb7VSK

Once the permissions are assigned, you need to disconnect the current session then login to a new session to get the changes. As you can see, in the below, the new permission has been assigned to the app.

PS C:\> Get-MgContext

ClientId               : 4ca434dd-463e-4124-9c06-46c765ca67da
TenantId               : c032627b-6715-4e39-9990-bcf48ee5e0c5
Scopes                 : {Directory.ReadWrite.All, User.Read.All}
AuthType               : AppOnly
TokenCredentialType    : ClientSecret

This time, you should be able to create a new user using Graph PowerShell without any issue.

PS C:\> New-MgUser @params -AccountEnabled -PasswordProfile $passwordProfile

DisplayName Id                                   Mail UserPrincipalName
----------- --                                   ---- -----------------
Test10      42844506-ddc3-4c76-8337-73426ab95c56      [email protected]

Conclusion

You learned how to connect to Microsoft Graph PowerShell with a client secret. Remember to update MS Graph module to the latest version, create an application and assign API permissions if you connect with client secret or CBA. With CBA, there is no more user interactions, usernames, passwords, or MFA involved to run automated scripts.

Not a reader? Watch this related video tutorial:

5/5 - (1 vote)
Previous Post

How to Connect to Graph PowerShell with Certificate Based Authentication

Next Post

How to Find All Parameters for a Cmdlet in PowerShell

Related Posts

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024
Ftr19

How to Fix Windows Cannot Read the ProductKey From the Unattend Answer File in VirtualBox

July 26, 2024
Ftr25

How to Update Windows Terminal in Windows 10/11

July 26, 2024

How to Disable The Beep Sound in WSL Terminal on Windows

July 26, 2024

Leave a Reply Cancel reply

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

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory