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

时间:2014-03-31 21:39:12

标签: php oauth-2.0 google-api-php-client google-admin-sdk server-to-server

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

我做了什么:

  1. 在Google Developers Console中创建了一个应用程序。
  2. 下载私钥并查找服务帐户名称。
  3. 在API下激活Admin SDK。
  4. 下载了google-api-php-client。
  5. 写了下面的代码:
  6. $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. 执行该小脚本会生成一个有效的访问令牌,有效期为一小时,并显示以下错误消息:
    2.   

      {"错误":{"错误":[{"域名":"全球","原因&#34 ;:"禁止","消息":"未授权访问此资源/ api" },"代码":403,"消息":"未授权访问此资源/ api" }}

      当我尝试使用我的PHP脚本中的访问密钥在Google OAuth操场上执行相同的请求时出现同样的错误。我是否必须在开发人员控制台的某处激活对该服务帐户的组数据的访问权限?

2 个答案:

答案 0 :(得分:0)

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

$auth->sub = $adminEmail;

出于某种原因,Admin SDK文档不包含PHP示例,但Google Drive文档中的instantiating a service account示例代码。

答案 1 :(得分:0)

我通过反复试验发现删除" admin。"来自范围使其有效(除了上述有关遵循这些步骤的所有内容: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
);