【问题标题】:Graph API Not retrieving data properly图形 API 未正确检索数据
【发布时间】:2019-02-08 07:17:58
【问题描述】:

我正在使用Microsoft graph API 使用php SDK (https://github.com/microsoftgraph/msgraph-sdk-php) 从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中设置了以下权限

以及在 azure 门户中

什么可能导致这个问题?有什么办法可以解决这个问题?

【问题讨论】:

    标签: php api microsoft-graph-api microsoft-graph-sdks


    【解决方案1】:

    你得到了异常:

    当前经过身份验证的上下文对此请求无效

    因为获取的令牌用于应用程序权限 (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();
    

    【讨论】:

    • 对此我不确定。但我尝试 /users/{user_email}/messages 没有运气。让我试试这个顺便说一句
    • 当使用/users/{user_id}/messages 查询时,它会导致 致命错误:未捕获的 GuzzleHttp\Exception\ClientException:客户端错误:GET https://graph.microsoft.com/v1.0/users/4eeeecfed49f7586/messages 导致401 Unauthorized 响应:{“错误”:{ "code": "NoPermissionsInAccessToken", "message": "令牌在 C:\wamp64\www\graph_api\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php 中不包含权限,或权限(截断...)第 113 行 错误。但它在图形资源管理器中给出结果 > developer.microsoft.com/graph/graph-explorer
    猜你喜欢
    • 2018-12-15
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    相关资源
    最近更新 更多