google-api-php-clientgoogle-admin-sdkgoogle-reporting-api

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


I'm having a problem when trying to access Admin SDK API to get some audit report using service account.

I've contacted to my workspace administrator to granted the Domain-wide Delegation with the service account clientID, which i created from my account project on https://console.cloud.google.com/. But when i do the same steps in quickstart.php, it always return this error with code 401:

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

Here is my script 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;
}

Solution

  • When using domain-wide delegation, you need to impersonate the user with the needed access permissions

    For accessing admin activity reports the request needs to be carried out on behalf of a user with admin privelleges:

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