【问题标题】:Impersonate google user with a service account使用服务帐户冒充 google 用户
【发布时间】:2013-02-20 21:02:36
【问题描述】:

我正在使用 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" }'"

【问题讨论】:

  • 我遇到了同样的问题,看来我应该对 google 配置本身进行一些更改。你找到解决方案了吗?你能指出我应该改变什么吗?
  • 你找到解决办法了吗?

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


【解决方案1】:

不要使用 $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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 2014-06-08
    • 2015-07-13
    • 2021-09-30
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多