Since your script is using the client credential flow, you cannot call the /me
endpoint. You need to grant the User.Read.All
application permission to the application, then call the /users/{user id}
endpoint.
require_once DIR . '/vendor/autoload.php';
// Include the Microsoft Graph classes
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;
// Data from Azure Active Diretory
$tenantId="xxx";
$clientId="yyy";
$clientSecret="zzz";
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'client_credentials',
],
])->getBody()->getContents());
$accessToken = $token->access_token;
// This works! The Access-Token is echoed
echo "AccessToken:".$accessToken;
// But from here on, i get no output
$graph = new Graph();
$graph->setAccessToken($accessToken);
$user = $graph->createRequest("GET", "/users/{user id}")
->setReturnType(Model\User::class)
->execute();
print_r($user);
echo "Hello, my name is {$user->getGivenName()}.";
If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.