使用 Microsoft Graph php 访问 OneDrive 文件

OneDrive file access with php using microsoft graph

我尝试使用 the library from krizalys 实现从 OneDrive 读取和写入文件。它应该适用于企业账户,但如果它也适用于个人账户就更好了。

因为我了解到 krizalys 示例中使用的 Live SDK 即将下线 (as mentioned here),所以我尝试实施 Microsoft Graph。

我目前实现了两种获取访问令牌的方法,一种是授权类型 password (getAccessToken Method from this sample used) and one with client_credentials (Like in the krizalys lib)。两者似乎都有效 return access_tokenrefresh_token,但是当我尝试发出请求时,我收到消息:

"InvalidAuthenticationToken [message] => Access token is empty"

我的请求代码:

$data = array("name" => "test");
$url  = "https://graph.microsoft.com/v1.0/me/drive/root";
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', $url, [
  'headers' => [
    'Authorization: Bearer ' . $this->_state->token->data->access_token,
    'Content-Type: application/json',
    'Content-Length: ' .strlen(json_encode($data))
   ],
   'body' => json_encode($data),
]);

我也用 GET 方法试过,并添加了 Host: graph.microsoft.com 以确保这不是问题所在:

$url = "https://graph.microsoft.com/v1.0/me";
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', $url, [
  'headers' => [
    'Authorization: Bearer ' . $this->_state->token->data->access_token,
    'Host: graph.microsoft.com'
  ],
]);

令牌响应负载如下所示:

应用程序已在https://apps.dev.microsoft.com配置并设置了权限。我的请求有什么问题吗?我不知道为什么我总是收到 InvalidAuthenticationToken 消息。谢谢。

您已在 v2 端点 (apps.dev.microsoft.com) 中注册您的应用程序,但您使用的示例代码适用于 v1 端点。这些不可互换。此外,password 不是 v2 端点的有效 OAuth 授权(v2 支持 authorization_codeimplicitclient_credentials

您需要从 v2 端点获取您的令牌。您可能会发现这些文章有帮助: