无法在Google服务帐户中使用子帐户

时间:2014-12-23 19:38:58

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

我需要创建一个脚本,将生成的屏幕截图上传到Google驱动器。

我希望我可以作为我的谷歌用户进行身份验证,但这似乎更难了?所以我放弃了那个机智。接下来我转到了服务帐户。这对我的服务帐户工作正常(现在),但是当我尝试指定用户($ auth-> sub)时,我得到“未经授权的客户端或请求范围。”。

function buildService($userEmail) {
  $DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
  $SERVICE_ACCOUNT_EMAIL = 'notsupplied@developer.gserviceaccount.com';
  $SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'pathtofile.p12';

  $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
  $auth = new Google_Auth_AssertionCredentials(
    $SERVICE_ACCOUNT_EMAIL,
    array($DRIVE_SCOPE),
    $key);
  $auth->sub = 'myuser@gmail.com';
  $client = new Google_Client();
  $client->setAssertionCredentials($auth);
  return new Google_Service_Drive($client);
}

我想放弃服务帐户,只需与我的常规Google用户一起使用即可轻松实现。或解决方法(在api设置中可能?)我可以确保可以使用myuser@gmail.com。

1 个答案:

答案 0 :(得分:0)

Refresh_token是这里的关键。在网络浏览器中,使用此链接批准您的Google用户:

https://accounts.google.com/AccountChooser?service=lso&continue=https%3A%2F%2Faccounts.google.com%2Fo%2Foauth2%2Fauth%3Fresponse_type%3Dcode%26scope%3Dhttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive%26redirect_uri%3Dhttps%3A%2F%2Fwww.example.com%2Foauth2callback%26access_type%3Doffline%26client_id%3D<CLIENT_ID>%26hl%3Den%26from_login%3D1%26as%3D34eac985232ba748&btmpl=authsub&hl=en&approval_prompt=force&access_type=offline

将返回https://www.example.com/oauth2callback?code=

之类的网址

然后将代码=&amp; client_id =&amp; client_secret =&amp; redirect_uri =&amp; grant_type = authorization_code发布到https://accounts.google.com/o/oauth2/token

这将返回&#34; refresh_token&#34;参数。保存这个。很重要。如果您没有获得,则必须转到https://security.google.com/settings/security/permissions以撤消您应用的权限。

获得刷新令牌后,您可以继续:

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$client->setAccessType('offline');
$token = $client->refreshToken('<YOUR_REFRESH_TOKEN>');
$service = new Google_Service_Drive($client);