首页 > 解决方案 > 如何让 Google 的 Oauth 屏幕加载到 Heroku 上 Flask 应用程序的窗口中

问题描述

我正在构建一个 Python Flask 应用程序,该应用程序收集有关用户的 Google 跟踪代码管理器 (GTM) 帐户的一些信息。为此,我需要他们授权对其 GTM 帐户的只读访问权限,然后我去检索我需要的数据。

这里的理想流程是:

  1. 用户点击“使用 Google 登录”
  2. 打开一个新标签页,要求他们选择他们的 Google 帐户
  3. 下一页告诉他们我正在寻找什么权限,并允许访问
  4. 他们接受,身份验证流程完成并且选项卡关闭。

我已经设法让应用程序以所需的流程在本地运行,没问题。

然而,一旦我将它部署到 Heroku,我遇到了一个障碍,因为身份验证流程根本不起作用。Heroku 的日志如下:

If your browser is on a different machine then exit and re-run this
application with the command-line parameter
 --noauth_local_webserver

我挖了一点,args.noauth_local_webserver = True作为参数添加到 Oauth Flow 对象中。

但是,这会产生一个新问题,在页面加载时,这会显示在 Heroku 的日志中:

Go to the following link in your browser:
https://accounts.google.com/o/oauth2/auth?client_id=629932623162-nguh8ssud6her0e6bbc5vloe1k3aq95q.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Ftagmanager.readonly&access_type=offline&response_type=code&prompt=select_account
Enter verification code:

这适用于我的本地环境,因为我可以访问该页面并将验证码粘贴到我的控制台中,但在 Heroku 上并没有真正有用。我不确定将验证码粘贴到哪里,如果我以外的其他人尝试登录,这肯定没有意义。

有谁知道我如何让用户的网络浏览器自动打开身份验证流程,而不是让它显示在控制台中?

如果有帮助,这是我正在使用的 GetService() 函数(来自 Google 的文档):

def GetService():

# Parse command-line arguments.
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
   parents=[tools.argparser])

flags = parser.parse_args([])
flags.noauth_local_webserver = True

# Set up a Flow object to be used if we need to authenticate.
flow = client.flow_from_clientsecrets(
   client_secrets_path, scope=scope,
   prompt = 'consent', 
   message=tools.message_if_missing(client_secrets_path)) 
   storage = file.Storage(api_name + '.dat')

credentials = storage.get()
if credentials is None or credentials.invalid: 
    credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())

# Build the service object.
service = build(api_name, api_version, http=http)

return service

然后我使用如下调用从服务对象中检索数据:

def retrieveAcctList():
    accountObj = GetService().accounts().list(
        access_token = token).execute()

这会触发我本地机器上的流程。

任何帮助表示赞赏!

标签: pythonflaskherokuoauth-2.0

解决方案


推荐阅读