【问题标题】:How to get an authorization code via HTTP request for Google OAuth 2.0 Playground - Python如何通过 HTTP 请求获取 Google OAuth 2.0 Playground 的授权码 - Python
【发布时间】:2021-10-20 17:27:00
【问题描述】:

我需要一些有关 Google OAuth 2.0 Playground 的帮助,希望有人能提供帮助。 我想知道如何通过 python 对 Google OAuth 2.0 Playground 的 HTTP 请求获取授权码?可能吗? 我正在尝试获取执行此请求的授权代码:

我试图转发这篇文章所期望的授权代码:

我的主要代码:

auth_url = "https://accounts.google.com/o/oauth2/auth"
access_token_url = "https://accounts.google.com/o/oauth2/token"
callback_url = "https://developers.google.com/oauthplayground"

client_id = 'xxx'
client_secret = xxx'

authorization_redirect_url = auth_url + '?response_type=code&client_id=' + client_id + '&redirect_uri=' + callback_url + '&scope=openid'
authorization_code = requests.get(authorization_redirect_url)

data = {'grant_type': 'authorization_code', 'code': authorization_code, 'redirect_uri': callback_url}
access_token_response = requests.post(access_token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))

如果我尝试运行我的代码,我会得到:

response:
{'Date': 'Wed, 18 Aug 2021 23:35:42 GMT', 'Expires': 'Mon, 01 Jan 1990 00:00:00 GMT', 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate', 'Pragma': 'no-cache', 'Content-Type': 'application/json; charset=utf-8', 'Vary': 'Origin, X-Origin, Referer', 'Content-Encoding': 'gzip', 'Server': 'scaffolding on HTTPServer2', 'X-XSS-Protection': '0', 'X-Frame-Options': 'SAMEORIGIN', 'X-Content-Type-Options': 'nosniff', 'Alt-Svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"', 'Transfer-Encoding': 'chunked'}
body: {
  "error": "invalid_grant",
  "error_description": "Malformed auth code."
}

有什么建议吗?

亲切的问候, 朱利亚诺

【问题讨论】:

  • 要获取代码,您需要启动一个网络服务器来响应redirect_url 回调。我写了一篇文章,解释了 curl 中的过程,包括一个特殊的 python web 服务器来响应 OAuth 回调:jhanley.com/google-oauth-2-0-testing-with-curl-version-2
  • 嗨@JohnHanley,我会读你的文章。谢谢

标签: python google-cloud-platform google-cloud-pubsub oauth2-playground


【解决方案1】:

抱歉,如果我错过了您的意图;不清楚您为什么要使用 OAuth Playground 自动化流程。

如果您尝试为 Google 的任何服务自动化 OAuth 流程,我鼓励您使用 Google 的 (Python) SDK,而不是手动编写自己的身份验证代码。

例如,请参阅为(该)Gmail 服务记录的 OAuth 流程 here

Google API 的优势在于每项 Google 服务都有一个 API,一旦您熟悉了一项服务的机制,您就可以将这些原则应用于每项服务。

【讨论】:

  • 您好 Daz,谢谢 :) 我正在通过 OAuth 操场执行此流程,因为有人告诉我这样做。这就是我正在工作的这个项目的身份验证层运行的方式。这可能是一个糟糕的解决方案,我们正在尝试找出一种更好的方法,我将按照您的建议尝试使用 Google 的 (Python) SDK。谢谢你:)
  • 我做到了,我现在可以通过 Google 的 (Python) SDKs 获取令牌。但是,当我尝试在谷歌云平台中执行我的代码时,它开始需要我的用户帐户。如何设置身份验证?谢谢
  • 太棒了!我引用的示例显示了如何将这些凭据应用到 Gmail。您应该能够将其用作您正在使用的服务的模板。
  • 嗨,Daz,每次我需要运行我的代码时都会弹出同意屏幕,这很烦人,有没有办法避免这种情况?谢谢:)
  • 如果您按照 Gmail 示例进行操作,则只有在如果您的凭据未在本地保留时,同意屏幕才会提示您。运行一次后,凭据(包括访问和刷新令牌)应在本地持久保存,并且在凭据失效之前不需要同意屏幕提示您。
猜你喜欢
  • 2020-04-11
  • 1970-01-01
  • 2017-11-07
  • 1970-01-01
  • 2020-08-17
  • 2013-03-16
  • 2017-12-25
  • 2020-12-11
  • 1970-01-01
相关资源
最近更新 更多