user3347814
user3347814

Reputation: 1133

How to authenticate Google Services in Google Colaboratory without user interaction?

I use the following to access bouth Google Drive and Google Sheets in my Google Colab Notebook:

# Mount Google Drive
from google.colab import drive
drive.mount('/content/drive')

# Google Sheets

from google.colab import auth
auth.authenticate_user()

import gspread
from google.auth import default
creds, _ = default()

gc = gspread.authorize(creds)

from gspread_dataframe import get_as_dataframe, set_with_dataframe

My problem with this is that it asks for the user to confirm the authentication in a pop-up and I want to use colabctl (https://github.com/bitnom/colabctl) to automate the execution of some scripts, so I need to execute the authentication part without user interaction.

Upvotes: 4

Views: 9121

Answers (1)

Lich
Lich

Reputation: 491

As a possible solution, I may suggest using Service Account.

  1. Go to GCP Console

  2. Select your current project (or create a new one): select GCP project

  3. Once the project is selected, go to IAM and Admin -> Service accounts -> + Create service account: create service account

  4. Next, you'll see a create service account prompt, which consists of 3 form steps. Fill in step 1 with any data you want. Skip steps 2 and 3.

  5. You'll be redirected to the new service account page. Note an Email field there. You may share any Google Drive content for that email address (same as you do for users' personal email addresses).

  6. Now you need to create a service account key, so you could use it to authenticate your script (select JSON key type): create service account JSON key

  7. After step 6, you should get your JSON key file downloaded. Put it into your Google Colab files. You may do something like that to initialize your google client (gc) :

import gspread

gc = gspread.service_account(filename='/content/credentials.json')

Important: gspread version should be >=3.6.0 to support service_account() method.

Note: See my example to list all shared Google Sheets using gspread: personal notebook example

Upvotes: 4

Related Questions