Share via

powershell - graph

Arkhaam 1 Reputation point
2021-08-26T13:04:03.973+00:00

hello,
I am trying to access Microsoft Graph in powershell for the first time and therefore I am using examples found on the internet.
Unfortunately when I try to run my first script, I get my connection token, but I get an error message: The remote server returned an error: (401) Unauthorized.

When declaring my application on Azure, however, I authorized the rights to the user.read.all libraries in delegated and in application ....

Do you have any idea where my problem came from?

Here is my code (app id and secret are masked for the sample):

$tenant = Read-Host("Enter Tenant Name :")
$openid = Invoke-RestMethod -uri "https://login.microsoftonline.com/$tenant/.well-known/openid-configuration"

write-host "The token endpoint of your directory is :"
$openid.token_endpoint

$token = $openid.token_endpoint


$body = @{
    client_id = *my App ID is Here*
    client_secret = *my App Secret Is Here*
    redirect_uri = "https://localhost"
    grant_type = "client_credentials"
    ressource ="https://graph.microsoft.com"
    tenant = $tenant
}

Write-Host "requesting access token"

$request = Invoke-RestMethod -uri $token -Body $body -Method Post
$request.access_token

$graph = "https://graph.microsoft.com/v1.0/users"

$api = Invoke-RestMethod -Headers @{Authorization = "Bearer $($request.access_token)"} -Uri $graph -Method Get
$api.value
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

1 answer

Sort by: Most helpful
  1. Limitless Technology 40,106 Reputation points
    2021-08-27T13:43:57.74+00:00

    Hi @Arkhaam

    As this is your first time I would suggest you to have a look at this and brush up the basics
    https://learn.microsoft.com/en-us/graph/powershell/get-started

    The remote server returned an error: (401) Unauthorized for this error and for this
    Various exchange services can be tested with online test connectivity tool from Microsoft. You may test the EWS connectivity as follows and see it works. If not adjust the code or server settings.

    1. Open https://testconnectivity.microsoft.com.
    2. Select Exchange Server as per your setup.
    3. Select Service Account Access and perform Test. Use the same parameters you use in code

    Hope this Answers all your queries , if not please do repost back .
    If an Answer is helpful, please click "Accept Answer" and upvote it : )

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.