Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Login on colab with gcloud without service account

I'm trying to authenticate on a colab file to be able to make bigquery requests, access drive, etc. I've been using :

from google.colab import auth
auth.authenticate_user()

Which works great but asks for credentials every time the session times out (every 12h I think) and which requires human interaction (clicking on the link, copy the token, paste it).

I know I can use gcloud cli to authenticate using a 'service account'. But I don't have access to it in the organization I'm working in. However, I can get an access-token and an identity-token from gcloud.

Is there a way to authenticate using these tokens, simply by running a cell, and without further interactions ? What is the purpose of these tokens anyway ?

P.S: I'm okay with hacky solutions.

like image 469
Omar Aflak Avatar asked Dec 18 '22 15:12

Omar Aflak


1 Answers

This is how I did :

Step 1 : Sign In manually once

from google.colab import auth
auth.authenticate_user()

Step 2 : Dump keys

!cat adc.json

Then copy the values of the following keys : client_id, client_secret, refresh_token

Step 3 : Run that code whenever you want to authenticate

!pip install -U -q PyDrive

import httplib2
import json

from google.colab import auth
from oauth2client import GOOGLE_REVOKE_URI, GOOGLE_TOKEN_URI, client
from oauth2client.client import GoogleCredentials
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

auth_key = {
  "client_id": "...",
  "client_secret": "...",
  "refresh_token": "..."
}

credentials = client.OAuth2Credentials(
    access_token=None,
    client_id=auth_key['client_id'],
    client_secret=auth_key['client_secret'],
    refresh_token=auth_key['refresh_token'],
    token_expiry=None,
    token_uri=GOOGLE_TOKEN_URI,
    user_agent=None,
    revoke_uri=GOOGLE_REVOKE_URI)

credentials.refresh(httplib2.Http())
credentials.authorize(httplib2.Http())
cred = json.loads(credentials.to_json())
cred['type'] = 'authorized_user'

with open('adc.json', 'w') as outfile:
  json.dump(cred, outfile)

auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = credentials
drive = GoogleDrive(gauth)

Now you don't have to do any interaction with the browser, just run the cell.

like image 92
Omar Aflak Avatar answered Dec 28 '22 10:12

Omar Aflak