Gmail API会返回403错误代码,并且“拒绝委派” ”

问题描述 投票:23回答:3

检索包含此错误的邮件时,某个域的Gmail API失败:

com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 OK
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Delegation denied for <user email>",
    "reason" : "forbidden"
  } ],
  "message" : "Delegation denied for <user email>"
}

我正在使用OAuth 2.0和Google Apps域范围的授权来访问用户数据。域已授予应用程序的数据访问权限。

oauth-2.0 google-oauth gmail-api google-api-php-client
3个回答
44
投票

似乎最好的办法就是在请求中始终使用userId =“me”。这告诉API只使用经过身份验证的用户的邮箱 - 无需依赖电子邮件地址。


1
投票

我们的用户已迁移到域中,并且他们的帐户附加了别名。我们需要将SendAs地址默认为其中一个导入的别名,并希望有一种方法来自动化它。 Gmail API看起来像是解决方案,但我们的特权用户具有更改帐户的角色无效 - 我们一直看到“拒绝委托”403错误。

以下是我们如何列出其SendAs设置的PHP示例。

<?PHP

//
// Description:
//   List the user's SendAs addresses.
//
// Documentation:
//   https://developers.google.com/gmail/api/v1/reference/users/settings/sendAs
//   https://developers.google.com/gmail/api/v1/reference/users/settings/sendAs/list
//
// Local Path:
//   /path/to/api/vendor/google/apiclient-services/src/Google/Service/Gmail.php
//   /path/to/api/vendor/google/apiclient-services/src/Google/Service/Gmail/Resource/UsersSettingsSendAs.php
//
// Version:
//    Google_Client::LIBVER  == 2.1.1
//

require_once $API_PATH . '/path/to/google-api-php-client/vendor/autoload.php';

date_default_timezone_set('America/Los_Angeles');

// this is the service account json file used to make api calls within our domain
$serviceAccount = '/path/to/service-account-with-domain-wide-delagation.json';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $serviceAccount );

$userKey = '[email protected]';

// In the Admin Directory API, we may do things like create accounts with 
// an account having roles to make changes. With the Gmail API, we cannot 
// use those accounts to make changes. Instead, we impersonate
// the user to manage their account.

$impersonateUser = $userKey;

// these are the scope(s) used.
define('SCOPES', implode(' ', array( Google_Service_Gmail::GMAIL_SETTINGS_BASIC ) ) );

$client = new Google_Client();
$client->useApplicationDefaultCredentials();  // loads whats in that json service account file.
$client->setScopes(SCOPES); // adds the scopes
$client->setSubject($impersonateUser);  // account authorized to perform operation

$gmailObj  = new Google_Service_Gmail($client);

$res       = $gmailObj->users_settings_sendAs->listUsersSettingsSendAs($userKey);

print_r($res);


?>

1
投票

我想访问新电子邮件ID /帐户的电子邮件,但发生的事情是,最近创建的包含JSON的'.credentials'文件夹与我之前尝试过的先前电子邮件ID /帐户相关联。 JSON中存在的访问令牌和其他参数与新的电子邮件ID /帐户无关。因此,为了使其运行,您只需删除'.credentails'文件夹并再次运行该程序。现在,该程序打开浏览器并要求您授予权限。

删除python中包含文件的文件夹

import shutil
shutil.rmtree("path of the folder to be deleted")

你可以在程序结束时添加它

© www.soinside.com 2019 - 2024. All rights reserved.