0

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;
}
Hung Dang
  • 55
  • 5

1 Answers1

1

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>')

ziganotschka
  • 25,866
  • 2
  • 16
  • 33
  • Thanks for reply, so i have to setSubject to email of any user which they have the access permissions to admin audit reports? I see in the Role Managements, i can create a custom role then check on ````Report```` privileges, right? – Hung Dang Oct 02 '21 at 05:21
  • Thanks so much, i tried to grant the privilege ````Reports```` for the user, and the API can return the response, but i have other problem with the API result, looks like it's not realtime – Hung Dang Oct 04 '21 at 01:10
  • 1
    Glad it works fo you! AS for the delay - this is a different question, but have a look here: https://support.google.com/a/answer/7061566?hl=en – ziganotschka Oct 04 '21 at 05:27
  • I've already read this post, a little bit disappointed when the report not realtime...:( – Hung Dang Oct 04 '21 at 14:04