"Insufficient privileges to complete the operation" 尝试连接到 Microsoft Graph 时

"Insufficient privileges to complete the operation" when trying to connect to Microsoft Graph

我想配置我的 Symfony4 应用程序以使用 msgraph-sdk-php 库阅读和发送电子邮件。

我的应用程序将从单个帐户读取和发送电子邮件,我不想将其密码暴露给应用程序的用户。因此,我不会使用 OAuth 进行登录。

我的第一次体验是这段代码(检索邮箱用户资料):

<?php

namespace App\Graph;

use Microsoft\Graph\Exception\GraphException;
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model\User;

class GraphService
{
    function sentTestMessage() {
        $userId = "************************************";
        $tenantId = "************************************";
        $clientId = "************************************";
        $clientSecret = "***************************";


        $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;


        $graph = new Graph();
        $graph->setAccessToken($accessToken);

        $user=new \stdClass();
        try {
            $user = $graph->createRequest("GET", "/users/".$userId)
                ->setReturnType(User::class)
                ->execute();
        } catch (GraphException $e) {
            $user->getGivenName=$e->getMessage();
        }

        return "Hello, I am $user->getGivenName() ";

    }
}

但随后 Symfony 向我显示了一个包含以下消息的异常页面:

Client error: GET https://graph.microsoft.com/v1.0/users/... resulted in a 403 Forbidden response:

{

"error": {

"code": "Authorization_RequestDenied",

"message": "Insufficient privileges to complete the ope (truncated...)

现在,当 https://developer.microsoft.com/en-us/graph/graph-explorer 中的 运行 与同一用户登录时,相同的查询有效。

这些是我授予应用程序的权限:

我应该怎么做才能克服上述问题?

您在代码中使用了客户端凭据流来获取访问令牌,因此您需要 application permission 而不是委派权限。