Get GoogleCredentials from localhost (without specifiying serviceAccount/privateKey)

1/16/2019

I am both locally, as well as within our Kubernetes pods, authenticated into Google cloud. On both I can get correct response with gcloud info.

However, when I want to access GoogleDrive, I need to use GoogleCredential as follows:

        GoogleCredential.Builder()
                .setTransport(transport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountPrivateKey(privateKey)
                .setServiceAccountId(serviceAccount)
                .setServiceAccountScopes(scopes.toList()).build()

Meaning - I need to specifically set privateKey and serviceAccount. Is there a way to force it to use the locally authenticated account?

When using Google buckets this can be done quite easily:

StorageOptions.getDefaultInstance().service.options.credentials

I cannot find the same way for Google Drive.

-- Vojtěch
gcloud
google-drive-api
google-kubernetes-engine
java

1 Answer

1/23/2019

As @DazWilkin indicated, many GCP client libraries (such as GCS in your case) know how to automatically detect "Application Default Credentials" available.

These ADC credentials currently work only on Google Cloud Platform APIs (Google Drive predates that). You can read Google Drive Java quickstart to learn how to retrieve credentials: https://developers.google.com/drive/api/v3/quickstart/java

For refernce, GCP client libraries will look for ADCs by:

  1. GOOGLE_APPLICATION_CREDENTIALS environment variable, if set, pointing to JSON key file of the service account.
  2. Find %APPDATA%/gcloud/application_default_credentials.json (Windows) or $HOME/.config/gcloud/application_default_credentials.json (other) if the user has executed gcloud auth application-default login command.
  3. On Google App Engine 1st gen (not GAE Flex) use appengine.AccessToken API.
  4. On GCE, GKE or GAE 2nd gen environments, it calls the GCE Metadata API (an url like http://metadata.google.internal or http://169.254.169.254) to retrieve a short-lived access_token.

In your case, your GKE pods are using method #4 to retrieve a token for GCS bucket operations; but not for Drive API.

-- AhmetB - Google
Source: StackOverflow