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 Get an Access Token for Microsoft Graph PowerShell / API

November 27, 2023
in Blog, Microsoft Graph, Powershell
0
ADVERTISEMENT

Table of Contents

There are multiple methods of obtaining an access token for the Graph API, but an easy method is to use the Microsoft Authentication Library PowerShell Module (MSAL.PS).

Before you begin

Regardless the way you’re using to acquire an access token. An app registration must be created on Microsoft Entra ( aka Azure Active Directory ).

  • Create an app registration in Microsoft Entra admin center.
  • Grant the needed permissions to the app
  • Create client secret or upload a certificate to the app for authentication.

Without any module

Once the app has been created and you’ve collected all needed information such as client id, tenant id and client secret. The below script will be used to retrieve an access token.

#Get access token
$clientId = "ffb97f4f-cd58-4e4d-95ac-17081063c20b"
$tenantId = "c032627b-6715-4e39-9990-bcf48ee5e0c5"
$clientSecret = "vUm8Q~xxxxxxxxx.xxxxxxxxxxxxxxx"
$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

$Body = @{    
    Grant_Type    = "client_credentials"
    Scope         = "https://graph.microsoft.com/.default"
    client_Id     = $clientId
    Client_Secret = $clientSecret
} 

$authToken = Invoke-RestMethod -Uri $uri -Method POST -Body $Body
$token = $authToken.access_token

Using this method, you don’t need to install any PowerShell module such as Microsoft Graph PowerShell SDK or MSAL module. So, you can acquire the token on any computer with PowerShell installed.

PS P:\> $authToken

token_type expires_in ext_expires_in access_token
---------- ---------- -------------- ------------
Bearer          28799          28799 eyJ0eXAiOiJKV1QiLCJub25jZSI6ImdNQzNwdFVXT...

PS P:\> $token
eyJ0eXAiOiJKV1QiLCJub25jZSI6ImdNQzNwdFVXTFJqLW11dC04S01jMlNQZnRSSkhXOWhNSW5WV09NVHdLVVEiLCJhbGciOiJSUzI1NiIsIng1dCI6IjlHbW55RlBraGMzaE91UjIybXZTdmduTG83WSIsImtpZCI6IjlHbW55RlBraGMzaE91UjIybXZTdmduTG83WSJ9.eyJhdWQiOiJodHRwczovL2dyYXBoLm1pY3Jvc29mdC5jb20iLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9jMDMyNjI3Yi02NzE1LTRlMzktOTk5MC1iY2Y0OGVlNWUwYzUvIiwiaWF0IjoxNjk3NTMzNzIxLCJuYmYiOjE2OTc1MzM3MjEsImV4cCI6MTY5NzU2MjgyMSwiYWlvIjoiRTJGZ1lOZ2owbkJ5TmI5WHl2dVVwYnRhK09ZOEFnQT0iLCJhcHBfZGlzcGxheW5hbWUiOiJNckdyYXBoIiwiYXBwaWQiOiJmZmI5N2Y0Zi1jZDU4LTRlNGQtOTVhYy0xNzA4MTA2M2MyMGIiLCJhcHBpZGFjciI6IjEiLCJpZHAiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9jMDMyNjI3Yi02NzE1LTRlMzktOTk5MC1iY2Y0OGVlNWUwYzUvIiwiaWR0eXAiOiJhcHAiLCJvaWQiOiJmMGZlNDIxMS0zNmVkLTRhMzEtYWZmOC1hZWNlNTdhYWI2MTEiLCJyaCI6IjAuQWJjQWUySXl3QlZuT1U2WmtMejBqdVhneFFNQUFBQUFBQUFBd0FBQUFBQUFBQUMzQUFBLiIsInJvbGVzIjpbIk1haWwuUmVhZFdyaXRlIiwiVXNlci5SZWFkV3JpdGUuQWxsIiwiRGlyZWN0b3J5LlJlYWRXcml0ZS5BbGwiLCJGaWxlcy5SZWFkV3JpdGUuQWxsIiwiTWFpbGJveFNldHRpbmdzLlJlYWRXcml0ZSIsIkF1ZGl0TG9nLlJlYWQuQWxsIl0sInN1YiI6ImYwZmU0MjExLTM2ZWQtNGEzMS1hZmY4LWFlY2U1N2FhYjYxMSIsInRlbmFudF9yZWdpb25fc2NvcGUiOiJOQSIsInRpZCI6ImMwMzI2MjdiLTY3MTUtNGUzOS05OTkwLWJjZjQ4ZWU1ZTBjNSIsInV0aSI6InVBTWZydUpLNUUtWTZVN0hKbk1tQUEiLCJ2ZXIiOiIxLjAiLCJ3aWRzIjpbIjA5OTdhMWQwLTBkMWQtNGFjYi1iNDA4LWQ1Y2E3MzEyMWU5MCJdLCJ4bXNfdGNkdCI6MTY4OTIzOTM5NH0.oylQH4FE7zSd-uSMJqq0bGThJHqL3VhLe7piq4L0Il1yRx_qlaqBoxLza8WuXW6jbxuuoUnxgAxZfj0wNJHMKLuKszc9AxWeo

MSAL.PS

The second way, an access token can be retrieve using MSAL.PS module. Before you begin, make sure the module has been installed by the below command:

Install-Module -Name MSAL.PS
# Get the installed PowerShell module
PS C:\> Get-InstalledModule -Name MSAL.PS

Version              Name                                Repository      
-------              ----                                ----------      
4.37.0.0             MSAL.PS                             PSGallery

Once the module has been installed. We can get the access token using a native cmdlet Get-MsalToken. And of course, we still need client id, tenant id and client secret for authentication.

Import-Module MSAL.PS

$ClientId = "ffb97f4f-cd58-4e4d-95ac-17081063c20b"
$TenantId = "c032627b-6715-4e39-9990-bcf48ee5e0c5"
$ClientSecret = "vUm8Q~xxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxx"

$secureSecret = $clientSecret | ConvertTo-SecureString -AsPlainText -Force
$msalToken = Get-MsalToken -ClientId $clientId -TenantId $tenantId -ClientSecret $secureSecret
PS P:\> $msalToken

AccessToken                  : eyJ0eXAiOiJKV1QiLCJtlebmFud...........CgmUn1x3aS7g
IsExtendedLifeTimeToken      : False
UniqueId                     : 
ExpiresOn                    : 10/17/2023 5:20:34 PM +00:00
ExtendedExpiresOn            : 10/17/2023 5:20:34 PM +00:00
TenantId                     : 
Account                      : 
IdToken                      : 
Scopes                       : {https://graph.microsoft.com/.default}
CorrelationId                : 70d05702-859e-4570-80ae-6e7884fb4b93
TokenType                    : Bearer
ClaimsPrincipal              : 
AuthenticationResultMetadata : Microsoft.Identity.Client.AuthenticationResultMetadata
User                         : 

Connect to Microsoft Graph using the Access Token

The access token can be used for automations tasks depending on your requirements. For a basic example, we use the token (got from MSAL) to connect to Microsoft Graph PowerShell as follows:

$token = ($msalToken.AccessToken | ConvertTo-SecureString -AsPlainText -Force)
Connect-Graph -AccessToken $token
PS P:\> Connect-Graph -AccessToken $token

Welcome to Microsoft Graph!

Connected via userprovidedaccesstoken access using ffb97f4f-cd58-4e4d-95ac-17081063c20b
Readme: https://aka.ms/graph/sdk/powershell
SDK Docs: https://aka.ms/graph/sdk/powershell/docs
API Docs: https://aka.ms/graph/docs

NOTE: You can use the -NoWelcome parameter to suppress this message.

PS P:\> Get-MgContext

ClientId               : ffb97f4f-cd58-4e4d-95ac-17081063c20b
TenantId               : c032627b-6715-4e39-9990-bcf48ee5e0c5
Scopes                 : {Mail.ReadWrite, User.ReadWrite.All, Directory.ReadWrite.All, Files…}
AuthType               : UserProvidedAccessToken
TokenCredentialType    : UserProvidedAccessToken
CertificateThumbprint  : 
CertificateSubjectName : 
Account                : 
AppName                : MrGraph
ContextScope           : Process
Certificate            : 
PSHostVersion          : 2023.8.0
ManagedIdentityId      : 
ClientSecret           : 
Environment            : Global

Call a Graph API endpoint with access token

Or you can use the Invoke-RestMethod cmdlet to call the Rest API with the obtained access token. The below script retrieves first five Entra ID users information.

$url = 'https://graph.microsoft.com/beta/users?$top=5'
$headers = @{
    Authorization = "Bearer $($msalToken.AccessToken)"
}

$users = (Invoke-RestMethod -Method GET -Headers $headers -Uri $url).Value
$users | select displayName, userPrincipalName, id, accountEnabled
displayName       userPrincipalName   id                                   accountEnabled
-----------       -----------------   --                                   --------------
Adele Vance       [email protected]    cd90a87a-7156-4f6a-88b5-5ee908354b3c           True
MOD Administrator [email protected]     647fea69-afca-4001-af45-f0cc82a2fa41           True
Alex Wilber       [email protected]     a1ae71c5-a099-4368-8c9f-c1e24cb027fc           True
Allan Deyoung     [email protected]    19d877b4-b2f8-456d-ad26-766dec8f5d74           True
Automate Bot      [email protected] 7a8b00ac-6c46-48b3-bc0e-4fc0b20be29b           True

Not a reader? Watch this related video tutorial:

5/5 - (1 vote)
Previous Post

Getting Access Token for Microsoft Graph

Next Post

How To Check Microsoft Office 365 Subscription Expiry Date

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