Call Workspace APIs locally (the right way)

This LAB is an implementation of principles describe in this blog post.

What the content of the LAB?

A simple python script that list the content (just filenames) of your Google Drive.

Note: don't trust me blindly, please read to main.py and requirements.txt by yourself!

This LAB aims to describe issues when interacting with a Workspace API using your user-credentials and how you can fix it.

Prerequisites:

  • python
  • gcloud

LAB

Setup

PROJECT=YOUR_PROJECT_ID

gcloud config set project $PROJECT

gcloud services enable drive.googleapis.com

gcloud iam service-accounts create demo-auth-workspace-apis

python3 -m venv venv && source venv/bin/activate

pip install -r requirements.txt

1. Test with user-credentials

gcloud auth application-default login

python main.py

You shloud see the following error:

2. Test with a service account impersonation

A way to fix this issue it so interact with Workspace API using a service account identity.

In order to work you will have to:

  1. Give demo-auth-workspace-apis@${PROJECT}.iam.gserviceaccount.com a viewer access to your Google Drive

  1. Run commands below:
export SA_TO_IMPERSONATE="demo-auth-workspace-apis@${PROJECT}.iam.gserviceaccount.com"

# Grant you to permission to impersonnate the targeted SA
gcloud iam service-accounts add-iam-policy-binding "${SA_TO_IMPERSONATE}" \
--member="user:$(gcloud auth list --filter=status=active --format='value(account)')" \
--role='roles/iam.serviceAccountTokenCreator'

# Enforce impersonation in ADC
# -> you need to reauthenticate by indicating the SA to impersonate in order to propagate the information
gcloud auth application-default login --impersonate-service-account=$SA_TO_IMPERSONATE

python main.py

Now, normally the script should work 🚀!

Note: if not please create an issue

The beauty is that you don't need to update the codebase. Here the power of ADC 💪💪💪.

Cleanup

gcloud iam service-accounts delete "demo-auth-workspace-apis@${PROJECT}.iam.gserviceaccount.com" -q
gcloud services disable drive.googleapis.com