无法通过OAuth对Google API进行经过身份验证的调用

无法通过OAuth对Google API进行经过身份验证的调用

问题描述:

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

When I try to make a call to the Google Directory API using Server to Server authentication, I get the error message "Not Authorized to access this resource/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. 执行该小脚本会产生一个有效的访问令牌,有效期为一个小时,并显示以下错误消息:

{"error":{"errors":[{"domain":"global","reason":"forbidden","message":未授权访问此资源/api"}],代码:403,"消息:"未授权访问此资源/api}}

{ "error": { "errors": [ { "domain": "global", "reason": "forbidden", "message": "Not Authorized to access this resource/api" } ], "code": 403, "message": "Not Authorized to access this resource/api" } }

当我尝试使用我的PHP脚本中的访问密钥在Google OAuth操场上执行相同的请求时,遇到相同的错误.我是否必须在开发人员控制台的某个位置激活对该服务帐户的组数据的访问?

I get the same error when I try to do the same request on the Google OAuth playground with the access key from my PHP script. Do I have to activate access to the group data for that service account somewhere in the Developers Console?

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

Beyond granting the service account client id access to the given scopes in your Google Apps Control Panel, you need to tell the service account to impersonate a super administrator user within your Google Apps domain:

$auth->sub = $adminEmail;

由于某些原因,Admin SDK文档不包含PHP示例,但是有

For some reason, the Admin SDK docs don't contain a PHP sample but there's sample code for instantiating a service account in the Google Drive docs.