403 Error in calling Google Admin SDK

时间:2015-09-01 22:35:01

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

I am trying to list the users in my google domain using the Admin SDK PHP library. However I am getting 403 users when I am trying to list my users. This is what I tried

$client = new Google_Client();
$client->setApplicationName("My Application");
$credential = new Google_Auth_AssertionCredentials(
            $serviceAccount,
            array('https://www.googleapis.com/auth/admin.directory.user'),
            $privateKey,
            'notasecret',
            'http://oauth.net/grant_type/jwt/1.0/bearer'
            );

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

$service = new Google_Service_Directory($client);

$optParams = array('domain' => 'mydomain');
$results = $service->users->listUsers($optParams);

But I get this 403 error

Error calling GET https://www.googleapis.com/admin/directory/v1/users?domain=mydomain: (403) Not Authorized to access this resource/api

As suggested in other similar posts, I also tried including the delegated admin as shown below

$credential                = new Google_Auth_AssertionCredentials(
            $serviceAccount,,
            array('https://www.googleapis.com/auth/admin.directory.user'),
            $privateKey,
            'notasecret',
            'http://oauth.net/grant_type/jwt/1.0/bearer',
             'admin@mydomain.com'
    );

But this gave the following error on refreshTokenWithAssertion($credential)

Error refreshing the OAuth2 token, message: '{
"error" : "unauthorized_client",
"error_description" : "Unauthorized client or scope in request."
}'

I verified the service account and also enabled the API in the project's console.Can anyone figure out what I am doing wrong ? Please help. I am struct at this for a while.

1 个答案:

答案 0 :(得分:1)

我找到了这个错误的解决方案。我在Google_Auth_AssertionCredentials中添加了“sub”,如下所示,并在admin.google.com-> Security->管理API访问和授权后添加了客户端ID和范围。

这个

$credential                = new Google_Auth_AssertionCredentials(
        $serviceAccount,,
        array('https://www.googleapis.com/auth/admin.directory.user'),
        $privateKey,
        'notasecret',
        'http://oauth.net/grant_type/jwt/1.0/bearer',
         'admin@mydomain.com', false
);

加上admin.google.com-的授权 - >安全性 - >管理API访问解决了这个问题。为什么我必须授权是一个不同的问题。