API Gmail возвращает 403 код ошибки и "Делегация отказана для <электронной почты пользователя>"

Ошибка API Gmail для одного домена при получении сообщений с этой ошибкой:

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 для доступа к пользовательским данным. Домен предоставил права доступа к данным для приложения.

Ответы

Ответ 1

Похоже, что лучше всего всегда иметь userId = "me" в ваших запросах. Это говорит API, чтобы просто использовать аутентифицированный почтовый ящик пользователя - нет необходимости полагаться на адреса электронной почты.

Ответ 2

Наши пользователи перешли в домен, и к их учетной записи присоединились псевдонимы. Нам нужно было по умолчанию отправить адрес SendAs на один из импортированных псевдонимов и попытаться автоматизировать его. API Gmail выглядел как решение, но наш привилегированный пользователь с ролями для внесения изменений в учетные записи не работал - мы все видели ошибку "Делегация отказала" для 403.

Вот пример PHP, как мы смогли перечислить их настройки SendAs.

<?PHP

//
// Description:
//   List the user 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);


?>