使用服务账号访问Admin SDK时如何处理"Access denied. You are not authorized to read activity records."API

How to deal with "Access denied. You are not authorized to read activity records." when using service account access Admin SDK API

我在尝试访问 Admin SDK API 以使用服务帐户获取一些 audit report 时遇到问题。

我已联系我的工作区管理员,以授予 Domain-wide Delegation 服务帐户 clientID,该帐户是我在 https://console.cloud.google.com/ 上的帐户项目中创建的。但是当我在 quickstart.php 中执行相同的步骤时,它总是 return 这个错误代码 401:

{
   "message": "Access denied. You are not authorized to read activity records.",
   "domain": "global",
   "reason": "authError",
   "location": "Authorization",
   "locationType": "header"
}

这是我的脚本PHP:

$sa_credential = '<path/to/my/redentials.json>';
try {
     $client = new Google\Client();
     if (file_exists($sa_credential)) {
        // set the location manually
        $client->setAuthConfig($sa_credential);
     } elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
        // use the application default credentials
        $client->useApplicationDefaultCredentials();
     } else {
         echo 'Missing credential file!';
         return;
     }
    $client->setApplicationName("PHP_Reports_API");
    $client->addScope('https://www.googleapis.com/auth/admin.reports.audit.readonly');
    $client->setSubject('<my_account_email>');
    $service    = new Google\Service\Reports($client);
    $userKey = 'all';
    $applicationName = 'login';
    $optParams = array(
                   'maxResults' => 10,
                 );
    $results = $service->activities->listActivities($userKey, $applicationName, $optParams);
    print_r($results);
    return $result;
} catch (Google_Service_Exception $ex) {
    print_r(json_encode($ex->getErrors()));
    return false;
}

使用全域委派时,您需要模拟具有所需访问权限的用户

要访问 admin activity reports,需要代表具有管理员权限的用户执行请求:

$client->setSubject('<emai_of_your_domain_admin>')