我正在尝试对colab文件进行身份验证,以便能够发出bigquery请求,访问驱动器等。我一直在使用:
from google.colab import auth
auth.authenticate_user()
哪种方法效果很好,但是每次会话超时(我认为每12小时)都会要求提供凭据,并且这需要人工干预(单击链接,复制令牌并粘贴)。
我知道我可以使用gcloud
cli通过“服务帐户”进行身份验证。但是我所在的组织没有访问它的权限。但是,我可以从gcloud获得access-token
和identity-token
。
是否有一种方法可以简单地通过运行单元并无需进一步交互来使用这些令牌进行身份验证?这些令牌的目的是什么?
PS:我对hacky解决方案没问题。
答案 0 :(得分:3)
这就是我的做法:
第1步:手动登录一次
from google.colab import auth
auth.authenticate_user()
第2步:转储密钥
!cat adc.json
然后复制以下键的值:client_id
,client_secret
,refresh_token
第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)
现在您不必与浏览器进行任何交互,只需运行单元格即可。