【问题标题】:OAuth on localhost and pythonanywhere本地主机和 pythonanywhere 上的 OAuth
【发布时间】:2020-08-25 21:34:43
【问题描述】:

我正在制作一个日历应用程序,它允许用户授予访问他们的谷歌日历的权限,然后我的应用程序将允许他们查看和编辑以我自己的自定义样式显示的日历。

它基于这个谷歌"quickstart" sample

它目前在本地运行良好,但到目前为止我还没有让它在 pythonanywhere.com 上运行(其中的 URL 将是 http://myname.pythonanywhere.com)。

在我的本地工作版本中,我使用的 credentials.json 文件以 "installed": 开头,其中 AFAICT 对应于“桌面应用程序”,"redirect_uris": 包含 ["urn:ietf:wg:oauth:2.0:oob", "http://localhost”]。 (“http://localhost”是有道理的,但我不知道为什么会有第二个 uri“urn:ietf:wg:oauth:2.0:oob”)

{
    "installed": {
        "client_id": "XXXXXXXXXXXXXXXX.apps.googleusercontent.com",
        "project_id": "my_great_calendar",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_secret": "XXXXXXXXXXXXX",
        "redirect_uris": [
            "urn:ietf:wg:oauth:2.0:oob",
            "http://localhost"
        ]
    }
}

如果我错了,请纠正我,但我假设这个 credentials.json 文件在托管在 myname.pythonanywhere.com 时可能无法工作,我需要创建一个新文件(在 Google 的“API 和服务”上) page) 通过将项目声明为“Web 应用程序”来制作?并告诉谷歌我的重定向 uri 是“http://myname.pythonanywhere.com”?

如果有一种方法可以让单个 credentials.json 文件在本地和 pythonanywhere 上都可以使用?

编辑: 快速入门示例使用InstalledAppFlow.from_client_secrets_file,我现在认为这是错误的。它可能需要以某种方式使用google_auth_oauthlib.flow.Flow.from_client_secrets_file() 来代替......如here 所述。

【问题讨论】:

    标签: python flask oauth-2.0 pythonanywhere


    【解决方案1】:

    您可以拥有一个支持多个重定向 URI 的单个客户端 ID/客户端密钥对:

    • 转到 API 和服务
    • 转到凭据
    • 查找您的客户 ID
    • 点击编辑(铅笔图标)
    • 在“授权的重定向 URI”下,您可以添加更多。
    • 保存

    然后 JSON 将包含两个重定向 URI。我不知道他们的库如何选择使用哪一个,因此您可能希望通过传递 redirect_uri 参数来明确指定它:

    flow = Flow.from_client_secrets_file('client_secrets.json', redirect_uri='http://blah.pythonanywhere.com/')
    

    要知道使用哪一个,您可以在启动服务器时传递一些配置(例如环境变量或命令行标志),或者让您的服务器通过 Host 标头自动检测它。

    【讨论】:

    • 为了首先获得客户端 ID,您必须单击“创建凭据”,然后单击“OAuth 客户端 ID”,然后选择“应用程序类型”——应该在那里选择什么?如果您选择“桌面应用程序”,它是否也可以在服务器上运行?如果您选择“网络应用程序”,它是否也可以在本地运行?在这两种情况下,你会在你的 python 代码中使用“InstalledAppFlow.from-client-secrets-file”吗?
    • 如果您想要一个桌面和网络应用程序,Google 的建议是创建 2 个客户端 ID,每个类型都正确。如果您在同一个项目中创建它们,一旦用户授权其中一个,其他人将不会重新请求授权,因此对用户是透明的。 developers.google.com/identity/protocols/oauth2/…
    • 遗憾的是,在这种情况下,您确实需要两个不同的 json
    猜你喜欢
    • 2011-11-29
    • 2014-08-12
    • 2010-10-22
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    相关资源
    最近更新 更多