我正在使用Microsoft graph API
(https://github.com/microsoftgraph/msgraph-sdk-php)通过php SDK
从Microsoft帐户检索我的消息。
我的代码示例如下
<?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;
但这会引发如下错误:
致命错误:未捕获的GuzzleHttp \ Exception \ ClientException:客户端错误:
GET https://graph.microsoft.com/v1.0/me/messages
导致400 Bad Request
响应:{“错误”:{“代码”:“ BadRequest”,“消息”:“当前经过身份验证的上下文对此请求无效。(被截断...)在第113行的C:\ wamp64 \ www \ graph_api \ vendor \ guzzlehttp \ guzzle \ src \ Exception \ RequestException.php中
这是由于访问Graph API的权限问题引起的吗?我在Microsoft app registration portal
以及天蓝色的门户网站
什么可能导致此问题?有什么办法解决问题吗?
答案 0 :(得分:5)
您遇到了例外情况:
当前已认证的上下文对此请求无效
因为获取的令牌用于应用程序许可(client credentials flow)。在此流程中,Me
没有上下文,因为它表示已登录的用户上下文。
要获取客户端凭据流中的消息,需要在端点中明确解析用户:
https://graph.microsoft.com/v1.0/users/{user-id}/messages
示例
$userId = "--user-id-goes-here--";
$messages = $graph->createRequest("GET", "/users/{$userId}/messages")
->setReturnType(\Microsoft\Graph\Model\User::class)
->execute();