使用Oauth2登录Google Colab

时间:2019-04-22 17:56:23

标签: python oauth oauth-2.0 google-oauth google-colaboratory

我正在尝试使用Oauth 2.0登录Google Colab笔记本,但是启动的Google登录网页以不存在的网站(http://localhost:8090/?code=4/NAFDWUxkOxp3FIlB9I_vxFTFm-zjAx0XJpEspQ9dGozG-0L3ccthFD12FAhq_B5hLWTxDFuUg_SjC011V9jiLDw&scope=https://www.googleapis.com/auth/admin.directory.group.member%20https://www.googleapis.com/auth/admin.directory.group%20https://www.googleapis.com/auth/apps.groups.settings)结尾。

也许该错误与任何回调URL有关,但我不知道如何解决。

这是我用于登录的代码。

import os
os.environ['USE_NATIVE_IPYTHON_SYSTEM_COMMANDS'] = '1'

import httplib2

from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run_flow
from oauth2client import tools

from google.colab import drive; drive.mount('/content/drive')

PATH_BASE = '/content/drive/My Drive/.../'
CLIENT_SECRET = PATH_BASE + 'client_secret_event.json'
SCOPES = [ "https://www.googleapis.com/auth/admin.directory.group", "https://www.googleapis.com/auth/admin.directory.group.member", "https://www.googleapis.com/auth/apps.groups.settings"]
STORAGE = Storage(PATH_BASE + 'credentials.storage')
flags = tools.argparser.parse_args([])

# Start the OAuth flow to retrieve credentials
def authorize_credentials():
    # Fetch credentials from storage
    credentials = STORAGE.get()
    # If the credentials doesn't exist in the storage location then run the flow
    if credentials is None or credentials.invalid:
        flow = flow_from_clientsecrets(CLIENT_SECRET, scope=SCOPES)
        http = httplib2.Http()
        credentials = run_flow(flow, STORAGE, flags, http=http)
    return credentials

credentials = authorize_credentials()

关于为什么会发生这种情况的任何想法?

3 个答案:

答案 0 :(得分:1)

有一个示例,该示例说明如何使用 InstalledAppFlow 通过python使用Google文档:

from google_auth_oauthlib.flow import InstalledAppFlow

有用的链接:

Using OAuth 2.0 for Installed Applications (with full example)

Sample Using Google Docs

答案 1 :(得分:0)

您将要使用Junfeng Zhang's MSDN blog about Sample Managed GAC API Wrappers而不是Web应用程序流。

原因是Colab后端没有直接暴露给Internet,因此无法处理基于Web的OAuth流常见的URL重定向。

答案 2 :(得分:0)

按照评论和 this 教程(您可以从中受益,在控制台中创建应用程序),我实现了以下代码:

creds = None

# Check if previous log-in exists
if os.path.exists('/content/drive/MyDrive/Projects/xyz/token.pickle'):
  with open('/content/drive/MyDrive/Projects/xyz/token.pickle', 'rb') as token:
    creds = pickle.load(token)

# If not available or invalid, log in using the "console" InstalledAppFlow
if not creds or not creds.valid:
  if creds and creds.expired and creds.refresh_token:
    creds.refresh(Request())
  else:
    flow = InstalledAppFlow.from_client_secrets_file('/content/drive/MyDrive/Projects/xyz/credentials.json', SCOPES)
    creds = flow.run_console()

  # Save the access token in token.pickle file for the next run
  with open('/content/drive/MyDrive/Projects/xyz/token.pickle', 'wb') as token:
    pickle.dump(creds, token)

# Connect to the Gmail API
service = build('gmail', 'v1', credentials=creds)