Reputation: 868
I am using Microsoft graph API
to retrieve my messages from Microsoft account using php SDK
(https://github.com/microsoftgraph/msgraph-sdk-php).
My code sample is given below
<?php
// Autoload files using the Composer autoloader.
require_once __DIR__ . '/vendor/autoload.php';
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;
//get the access token to access graph api
$tenantId = "XXXXXX";
$clientId = "XXXXXXXXXXXX";
$clientSecret = "XXXXXXXXXXX";
$guzzleClient = new \GuzzleHttp\Client(array('curl' => array( CURLOPT_SSL_VERIFYPEER => false)));
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzleClient->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;
//get the messages of user
$graph = new Graph();
$graph->setAccessToken($accessToken);
$messages = $graph->createRequest("GET", "/me/messages")
->setReturnType(Model\User::class)
->execute();
print_r($messages); exit;
But it throws me error as shown below :
Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error:
GET https://graph.microsoft.com/v1.0/me/messages
resulted in a400 Bad Request
response: { "error": { "code": "BadRequest", "message": "Current authenticated context is not valid for this request. (truncated...) in C:\wamp64\www\graph_api\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 113
Is this because of any permission problem to access the Graph API? I have the following permissions set in the Microsoft app registration portal
As well as in azure portal
What may cause this issue? Any way to solve the problem?
Upvotes: 1
Views: 1642
Reputation: 59318
You are getting the exception:
Current authenticated context is not valid for this request
since the acquired token is for application permissions (client credentials flow). In this flow, there is no context for Me
since it represents signed-in user context.
To get messages in client credentials flow user needs to be explicitly resolved in endpoint:
https://graph.microsoft.com/v1.0/users/{user-id}/messages
Example
$userId = "--user-id-goes-here--";
$messages = $graph->createRequest("GET", "/users/{$userId}/messages")
->setReturnType(\Microsoft\Graph\Model\User::class)
->execute();
Upvotes: 5