The AAD Graph PowerShell SDK allowed you to use a client secret for the Application only ( Service Principal ) login flow – also known as the client_credentials grant flow. The documentation for the new Microsoft Graph PowerShell SDK does not tell you how to use a client secret but instead, uses the more secure certificate method for the flow: Use app-only authentication with the Microsoft Graph PowerShell SDK | Microsoft Docs This post will show you how you can still use a client secret if you want by obtaining an access token and then using the -AccessToken parameter on the Connect-MgGraph command.

Assuming that you already have an app registration configured for this and it has the proper application permissions consented to for the request you want to make, we will use the PowerShell command “Invoke-RestMethod” to obtain an access token using the client_credentials grant flow.

$tenantId = "{your_tenant_id}"
$clientId = "{your_app_id}"
$clientSecret = "{your_client_secret}"

$body = @{
    grant_type="client_credentials";
    client_id=$clientId;
    client_secret=$clientSecret;
    scope="https://graph.microsoft.com/.default";
}

$response = Invoke-RestMethod -Method Post -Uri https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token -Body $body
$accessToken = $response.access_token

$accessToken

This first part of the script will obtain an access token with any consented Microsoft Graph application permissions. Once the access token is obtained, we can then set the -AccessToken parameter on the Connect-MgGraph request and make our graph requests accordingly.

Connect-MgGraph -AccessToken $accessToken
$user = Get-MgUser -Filter "userPrincipalName eq 'ray@mytesttenant.com'"

$user

Disconnect-MgGraph

Don’t forget to disconnect once you’re done. If you’re performing a long running task ( such as paging through records ) you may need to renew your access token with the same method as in the first part.

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments