[英]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 : 我正在尝试对colab文件进行身份验证,以便能够发出bigquery请求,访问驱动器等。我一直在使用:
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). 哪种方法效果很好,但每次会话超时时(我认为每12小时)都会要求提供凭据,并且需要人工干预(单击链接,复制令牌并粘贴)。
I know I can use gcloud
cli to authenticate using a 'service account'. 我知道我可以使用gcloud
cli通过“服务帐户”进行身份验证。 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. 但是我所在的组织中没有访问它的权限。但是,我可以从gcloud获得access-token
和identity-token
。
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 ? 这些令牌的目的是什么?
PS: I'm okay with hacky solutions. PS:我对hacky解决方案没问题。
This is how I did : 这是我做的:
Step 1 : Sign In manually once 第1步:手动登录一次
from google.colab import auth
auth.authenticate_user()
Step 2 : Dump keys 第2步:转储密钥
!cat adc.json
Then copy the values of the following keys : client_id
, client_secret
, refresh_token
然后复制以下键的值: client_id
, client_secret
, refresh_token
Step 3 : Run that code whenever you want to authenticate 步骤3:只要您想进行身份验证,就运行该代码
!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. 现在,您无需与浏览器进行任何交互,只需运行单元即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.