6

我正在使用 google-api-php-client 0.6.1,我想知道有没有办法用服务帐户模拟具体用户?我的应用程序需要在其谷歌驱动器中存储一些文件。因此,我决定使用用户服务帐户和 .p12 密钥 - 身份验证。它工作得很好,但所有文件都存储在服务帐户中,所以我无法管理它们。我希望将文档存储在某个帐户(用于创建 api 项目和服务帐户本身)中。我试图使用这段代码:

$KEY_FILE = <p12 key file path>;
$key = file_get_contents($KEY_FILE);
$auth = new Google_AssertionCredentials(
      $SERVICE_ACCOUNT_NAME,
      array('https://www.googleapis.com/auth/drive'),
      $key);
$auth->prn = '<certainuser@gmail.com>';
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);

但我收到“刷新 OAuth2 令牌时出错,消息:'{“error”:“access_denied”}'”

4

1 回答 1

2

不要使用 $auth->prn,使用 $auth->sub。这对我有用:

// Create a new google client.  We need this for all API access.
$client = new Google_Client();
$client->setApplicationName("Google Group Test");

$client_id = '...';
$service_account_name = '...';
$key_file_location = '...';

if (isset($_SESSION['service_token'])) {
    $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);

// https://www.googleapis.com/auth/admin.directory.group,
// https://www.googleapis.com/auth/admin.directory.group.readonly, 
// https://www.googleapis.com/auth/admin.directory.group.member, 
// https://www.googleapis.com/auth/admin.directory.group.member.readonly,
// https://www.googleapis.com/auth/apps.groups.settings, 
// https://www.googleapis.com/auth/books
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
        array(
            Google_Service_Groupssettings::APPS_GROUPS_SETTINGS,
            Google_Service_Directory::ADMIN_DIRECTORY_GROUP,
            Google_Service_Directory::ADMIN_DIRECTORY_GROUP_READONLY,

            Google_Service_Directory::ADMIN_DIRECTORY_GROUP_MEMBER,
            Google_Service_Directory::ADMIN_DIRECTORY_GROUP_MEMBER_READONLY,

            Google_Service_Books::BOOKS,
        ),
        $key,
        'notasecret'
    );
//
// Very important step:  the service account must also declare the
// identity (via email address) of a user with admin priviledges that
// it would like to masquerade as.
//
// See:  http://stackoverflow.com/questions/22772725/trouble-making-authenticated-calls-to-google-api-via-oauth
//
$cred->sub = '...';
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
于 2015-03-14T22:22:12.833 回答