Jump to content

How do I interact with Google Drive without manual authentication?


DeX

Recommended Posts

I already have the script working to access my Google Drive contents but at the beginning of the session the user must enter the Drive password, then the web application I built will work fine until that Drive access token expires (3600 seconds). Then you can either enter the password again or set up a refresh token to renew but I'm trying to avoid this initial manual login.

 

We use Google Drive for document management here in the office and all of our job files are stored there so anyone in the company with access can go in and look at any files related to a specific job in their Google Drive (via Shared With Me link). I'm building an area in our internal job management web application that will allow people to view these files in our portal and also upload new files through the portal that go into Google Drive into that job file's folder. 

 

These users using this portal have no idea what the login is for the main Drive administrator but this account will be used to access the files. Therefore when it prompts them for the password in my web application, they won't know it. I want it to just allow them access seamlessly, is this possible? I'm only granting them view and upload permissions and it's a small group of people I trust with those permissions.

 

The reason for the web application is because I built something that runs all of our job estimation and stores all of our quotes, customer profiles and purchase orders associated with each job. Everything is automatically generated with an estimated price so I would like to have another tab which shows all associated files to that job which have been uploaded to the main Google Drive account so everything is together in one place.

 

Does Google and OAuth2 even allow this?

Link to comment
Share on other sites

Slight problem. I created the service account, downloaded the JSON key file and pointed my application to it. Now when I try to open my web application, I get the error "Error: redirect_uri_mismatch." This is quite a common error on user accounts where you have not set your redirect URI in the permissions for that client ID account and you can easily fix it by adding the redirect URI, however, for a service account I cannot figure out anywhere to add redirect URI. Where to I add them? Should I even be getting this error on a service account?

Link to comment
Share on other sites

I assume it's similar to this: https://stackoverflow.com/questions/12710262/google-drive-redirect-uri-mismatch

 

Except you probably will need to select a different application type and set the redirect URI appropriately.

 

Close, but that's for creating a client ID for an Installed Application, I've already gotten it working that way but the access token keeps expiring and the user needs to log in every time. I'm trying to create a service account which has the benefit of automatic login without user interaction. With the service account specifically there is no place to add acceptable redirect URI.

Link to comment
Share on other sites

I got it, though it's incredibly slow and sometimes times out. I'll leave it here because I know others will be looking for this in the future.

 

0. Install the Google API using Composer, this is quite easy with some online tutorials.

1. Create a service account inside the Google Administrator interface. There are lots of other resources on this and it's easy.

2. Go to admin.google.com where you manage API client access. Enter your service account client ID in the first box and then "https://www.googleapis.com/auth/drive" into the second box. This is for full Drive access, you can also restrict the type by using something else.

3. Then you run your code, this is what I used:

<?php
    include_once __DIR__ . '/vendor/autoload.php';

    // location of credentials file downloaded from Google Drive
    $credentialsFile = '/var/client-service.json'; // you manually copy this file to your server

    // fail if our configuration file does not exist
    if (!file_exists($credentialsFile)) {
        throw new RuntimeException('Service account credentials Not Found!');
    }

    putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $credentialsFile);
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    // add full Drive scope, other options can be read only or metadata
    $client->addScope('https://www.googleapis.com/auth/drive'); // full Drive access

    $client->setAccessType('offline');
    // select user you want to impersonate
    $client->setSubject('your_user@email.com');
    $httpClient = $client->authorize();
    $service = new Google_Service_Drive($client);
    // specify parameters we want to work with, including folder name
// xxxxxxxxxxxxxxxxxx is the folder ID you want to read from
// get the folder ID from logging into that user's Google Drive
    $optParams = array(
        'pageSize' => 10,
        'fields' => "nextPageToken, files(contentHints/thumbnail,fileExtension,iconLink,id,name,size,thumbnailLink,webContentLink,webViewLink,mimeType,parents)",
        'q' => "'xxxxxxxxxxxxxxxxxx' in parents"
    );

    // list the files in the specified folder
    $files = $service->files->listFiles($optParams);

    // for testing, print file data so we can see it works
    foreach ($files as $file)
        print_r($file);

    // if desired, create a folder in this user's Drive
    $fileMetadata = new Google_Service_Drive_DriveFile(array('name' => 'Invoices3','mimeType' => 'application/vnd.google-apps.folder', 'folderId' => 'xxxxxxxxxxxxxxxxxx'));
    $newFile = $service->files->create($fileMetadata, array('fields' => 'id'));

?>

You have to create that service account and I believe I also created a project to link it to, these steps are in just about every tutorial I followed, what I could not find previously was how to impersonate the user so you weren't just interacting with the service account's Drive and this code shows how to do that. After creating your service account, it forces you to download the JSON file and this is the client-service.json file you will need to copy to your server at the location you specify near the top. Good luck, it's working for me.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.