2
votes

I am trying to create an app that (using a Drive service account) lists files in a given folder and allows users to search the content of those files. I am getting a 403 Insufficient Permissions error which I cannot explain.

I have edited the code from the Google API PHP Client Example:

$client_id = '[REMOVED]'; //Client ID
$service_account_name = '[REMOVED]'; //Email Address
$key_file_location = 'key.p12'; //key.p12

$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
service = new Google_Service_Drive($client);

if (isset($_SESSION['service_token'])) {
    $client->setAccessToken($_SESSION['service_token']);
}

$key  = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array(
        'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/drive.file'
    ),
    $key
);

$client->setAssertionCredentials($cred);

if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
}

$_SESSION['service_token'] = $client->getAccessToken();

$result = array();
$pageToken = NULL;

do {
    try {
        $parameters = array();
        if ($pageToken) {
            $parameters['pageToken'] = $pageToken;
        }

        $files = $service->files->listFiles($parameters);

        $result = array_merge($result, $files->getItems());

        $pageToken = $files->getNextPageToken();
    } catch (Exception $e) {
        echo "<br/>An error occurred: " . $e->getMessage();
        $pageToken = NULL;
    }
} while ($pageToken);

echo "<pre>";
print_r($result);
echo "</pre>";

echo "<br />Execution completed.";

The exact error message ($e->getMessage() in the catch above) is Error calling GET https://www.googleapis.com/drive/v2/files: (403) Insufficient Permission - I thought the /drive and /drive.file scopes gave me all the permissions I needed?

2
May be you have to add one more scope "googleapis.com/auth/drive.apps.readonly". Refer to this question for more details: stackoverflow.com/questions/22896018/… and also stackoverflow.com/questions/25032570/… . Hope that helps!KRR

2 Answers

3
votes

First, a quick note: You are requesting both the Drive scope and the Drive.File scope. The later is a subset of the former, so there is no need to request it. You should remove 'https://www.googleapis.com/auth/drive.file' line.

As to the insufficient permissions, this is possibility due to incorrect Developer Console configuration. You should double check that both the API and SDK are enabled for this particular project.

0
votes

I had the same issue. I created a new secret in the Google Developer Console and re-authenticated. This fixed the problem.