【问题标题】:"Access denied" exception is thrown, though the account has access尽管帐户具有访问权限,但引发“访问被拒绝”异常
【发布时间】:2015-07-22 07:07:04
【问题描述】:

我正在使用服务帐户来委派域范围的安全性,以便通过 Directory API 和 PHP 客户端库从我们的 Google Apps for Education 实例中提取用户列表。

我相当肯定我的服务帐户具有所有正确的安全性,因为它能够使用API reference's“试试”功能提取列表。

所以,在这一点上,一切都指向我的代码的问题,但我似乎无法弄清楚哪里:

<?php
require 'vendor/autoload.php';

$clientEmail = '<>@developer.gserviceaccount.com';
$privateKey = file_get_contents(__DIR__ . '/access.p12');
$scopes = array(
    'https://www.googleapis.com/auth/admin.directory.user.readonly',
);

$credentials = new Google_Auth_AssertionCredentials($clientEmail, $scopes, $privateKey);
$credentials->sub = 'service.account@my.domain';

$client = new Google_Client();
$client->setAssertionCredentials($credentials);

if ($client->getAuth()->isAccessTokenExpired()) 
{
    $client->getAuth()->refreshTokenWithAssertion();
}

$directory = new Google_Service_Directory($client);

$result = $directory->users->listUsers(array('domain' => 'my.domain'));

var_dump($result);

上面的代码抛出如下错误:

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: ' in C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php on line 358

Google_Auth_Exception: Error refreshing the OAuth2 token, message: '{
  "error" : "access_denied",
  "error_description" : "Requested client not authorized."
}' in C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php on line 358

Call Stack:
    0.0010     132792   1. {main}() C:\wamp\www\quick\index.php:0
    0.0260    1060248   2. Google_Auth_OAuth2->refreshTokenWithAssertion() C:\wamp\www\quick\index.php:18
    0.9230    1163560   3. Google_Auth_OAuth2->refreshTokenRequest() C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php:309

【问题讨论】:

    标签: php google-admin-sdk google-directory-api google-php-sdk


    【解决方案1】:

    调用堆栈应标识发生此错误的特定行。请注意,堆栈中的第二行似乎指向脚本的第 18 行,其中代码确实与 OAuth 验证有关:

    $client->getAuth()->refreshTokenWithAssertion();
    

    换句话说,当您尝试 refreshTokenWithAssertion 时,Google 会显示“access_denied 因为请求的客户端未授权”。如果您试图确定您在脚本中的哪个位置遇到了错误,我认为这应该可以回答您的问题。

    如果您想弄清楚为什么会出错,我会在 Google 上搜索 refreshTokenWithAssertion 以及该错误消息,看看是否有其他开发人员正在解决类似的问题.例如,通过 google 搜索,我发现 this other page on SO 可能会对您有所帮助。

    祝你好运!

    【讨论】:

    • 谢谢。我很欣赏你的建设性。它打开了门。
    • 太好了,很高兴我能帮上忙!
    猜你喜欢
    • 2020-04-02
    • 2018-12-27
    • 1970-01-01
    • 2017-02-16
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    相关资源
    最近更新 更多