Google API Insufficient Permissions listing files

2019-02-27 09:09发布

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条回答
Summer. ? 凉城
2楼-- · 2019-02-27 09:21

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

查看更多
We Are One
3楼-- · 2019-02-27 09:26

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.

查看更多
登录 后发表回答