具有默认凭据的Google_Service_Directory - 继续获取(403)未授权访问此资源/ api

时间:2016-12-08 23:41:13

标签: php api google-api google-api-php-client

我正在尝试使用default credentials获取有关群组的信息。我的代码是

        putenv( 'GOOGLE_APPLICATION_CREDENTIALS=' . XXX_SSO_SERVICE_ACCOUNT_CREDENTIALS_JSON );
        $service_account_client = new \Google_Client();

        $service_account_client->useApplicationDefaultCredentials();

        $service_account_client->setScopes([
            \Google_Service_Directory::ADMIN_DIRECTORY_GROUP_READONLY,
            \Google_Service_Directory::ADMIN_DIRECTORY_GROUP_MEMBER_READONLY,
            \Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY,
        ]);

        $groups_service = new \Google_Service_Directory( $service_account_client );
        $groups = $groups_service->groups->listGroups([
            'userKey' => 'contractor@xxx.com',
            'domain' => 'xxx.com'
        ]);

我一直收到错误“未授权访问此资源/ api”

我无法访问G Suite管理控制台,但我被告知已正确设置了perimissions。

我也尝试添加user to impersonate

的电子邮件
 $service_account_client = new \Google_Client( ['subject'=> 'admin@xxx.com'] );

但我仍然得到同样的错误。

1 个答案:

答案 0 :(得分:1)

在我的情况下,管理员用户不是admin@xxx.com而是另一封电子邮件。所以这里的正确答案是使用

    putenv( 'GOOGLE_APPLICATION_CREDENTIALS=' . XXX_SSO_SERVICE_ACCOUNT_CREDENTIALS_JSON );
    $service_account_client = new \Google_Client( ['subject'=> 'aaa.cccc@xxx.com'] );// Set the mail of an admin of G Suite

    $service_account_client->useApplicationDefaultCredentials();

    $service_account_client->setScopes([
        \Google_Service_Directory::ADMIN_DIRECTORY_GROUP_READONLY,
        \Google_Service_Directory::ADMIN_DIRECTORY_GROUP_MEMBER_READONLY,
        \Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY,
    ]);

    $groups_service = new \Google_Service_Directory( $service_account_client );
    $groups = $groups_service->groups->listGroups([
        'userKey' => 'contractor@xxx.com',
        'domain' => 'xxx.com'
    ]);