1

当我尝试使用服务器到服务器身份验证调用 Google Directory API 时,我收到错误消息“未授权访问此资源/api”。

我做了什么:

  1. 在 Google Developers Console 中创建了一个应用程序。
  2. 下载私钥并查找服务帐户名称。
  3. 激活 API 下的 Admin SDK。
  4. 下载了 google-api-php-client。
  5. 编写了以下代码:

$serviceAccountName = 'XXXXXXXXXXX@developer.gserviceaccount.com';
$scopes = 'https://www.googleapis.com/auth/admin.directory.group';
$privateKeyFile = dirname(__FILE__).'/../certs/googleapi-privatekey.p12';

$client = new Google_Client();
$client->setApplicationName('API Project');
$client->setScopes($scopes);
$cred = new Google_Auth_AssertionCredentials($serviceAccountName, $scopes, file_get_contents($privateKeyFile));
$client->setAssertionCredentials($cred);
$client->getAuth()->refreshTokenWithAssertion();

$req = new Google_Http_Request("https://www.googleapis.com/admin/directory/v1/groups/group-id@example.com/members?maxResults=1000");

$val = $client->getAuth()->authenticatedRequest($req);

var_dump($client->getAuth()->getAccessToken());
var_dump($val->getResponseBody());
  1. 执行该小脚本会产生一个有效的访问令牌,有效期为一小时,并显示以下错误消息:

{“错误”:{“错误”:[{“域”:“全局”,“原因”:“禁止”,“消息”:“未授权访问此资源/api”}],“代码”:403 , "message": "未授权访问此资源/api" } }

当我尝试使用我的 PHP 脚本中的访问密钥在 Google OAuth 操场上执行相同的请求时,我得到了同样的错误。我是否必须在 Developers Console 的某处激活对该服务帐户的组数据的访问权限?

4

2 回答 2

0

除了授予服务帐户客户端 ID 访问 Google Apps 控制面板中给定范围的权限外,您还需要告诉服务帐户在您的 Google Apps 域中模拟超级管理员用户:

$auth->sub = $adminEmail;

出于某种原因,Admin SDK 文档不包含 PHP 示例,但在 Google Drive 文档中有用于实例化服务帐户的示例代码。

于 2014-04-03T12:06:18.810 回答
0

我通过反复试验发现删除“管理员”。从范围使其工作(除了上面所说的关于遵循这些步骤的所有内容:https ://developers.google.com/drive/web/delegation#delegate_domain-wide_authority_to_your_service_account )。

$cs = json_decode(file_get_contents(<MY SECRET PATH> . 'client_secrets.json'), true); 
$cs = $cs['web'];
$cred = new Google_Auth_AssertionCredentials(
    $cs['client_email'], //why do they call this "service account name" ? Misleading >:(
    array(
        'https://www.googleapis.com/auth/directory.user',
        'https://www.googleapis.com/auth/directory.group',
        'https://www.googleapis.com/auth/directory.group.member'
    ),
    $key,
    'notasecret',
    'http://oauth.net/grant_type/jwt/1.0/bearer',
    '<MY EMAIL IN THE DOMAIN>' //_my_ email as an user with admin rights
);
于 2014-06-03T14:19:32.987 回答