【问题标题】:Google API invalid_grant / bad_requestGoogle API invalid_grant / bad_request
【发布时间】:2019-10-07 06:12:54
【问题描述】:

使用 python 3.6,请求==2.22.0

尝试使用 Google API,尤其是mobile and desktop apps flow

我可以使用这个 url 生成一个授权码:

url = (
    'https://accounts.google.com/o/oauth2/v2/auth?'
    'scope=email%20profile&'
    'response_type=code&'
    'redirect_uri={redirect_uri}&'
    'client_id={client_id}&'
    'access_type=offline'.format(
        redirect_uri=redirect_uri,
        client_id=client_id,
    )
)

我(目前)使用的redirect_uri 只是https://google.com,它在我生成的开发者应用程序中注册,在Authorized domains 部分下Authorized domains 部分的Authorized redirect URIs 部分OAuth consent settings 页面下/标签。

一旦我将生成的 url 粘贴到浏览器中 - 我会得到一个代码,我可以提取并使用它来进行下一次调用,该调用当前失败。

我确保将 "%2F" 替换为 "/"(使用 Firefox 时)。

接下来,我正在生成数据,并调用以用标记替换代码:

data = {
    'client_id': client_id,
    'client_secret': client_secret,
    'grant_type': 'authorization_code',
    'code': code,
    'redirect_uri': redirect_uri,
}
url = 'https://oauth2.googleapis.com/token'

response = requests.post(
    url,
    data=data,
    headers={
        'Content-Type': 'application/x-www-form-urlencoded',
    },

print(response)
print(response.json())

输出:

<Response [400]>
{'error': 'invalid_grant', 'error_description': 'Bad Request'}

【问题讨论】:

  • 无效授权通常意味着您发送的客户端 ID/密码/代码无效。
  • 你是对的@DaImTo - 这是代码 - 我清理不当

标签: python python-3.x python-requests google-oauth


【解决方案1】:

这是一个两年前的问题,但只是为了那些来到这里寻找答案的人。我遇到了@camelBack 遇到的同样问题,我解决的方法很简单。我删除凭据并再次运行授权流程。有了新的credentials.storage,问题就消失了。 更多信息@https://developers.google.com/identity/protocols/oauth2

对于那些在身份验证流程中苦苦挣扎的人,我在经过大量测试后意识到的一件事是您需要在 Jupyter Notebook 之外运行。打开终端并使用脚本本地运行 Python。它应该可以工作。

【讨论】:

  • 为什么不能在笔记本上运行呢?似乎您可以在笔记本中逐步执行此操作,不是吗?
  • 据我了解,这是一个限制。事实是,当您在笔记本上运行时,它不会启动流程。
猜你喜欢
  • 2019-03-18
  • 2014-06-24
  • 2014-08-26
  • 2014-06-19
  • 1970-01-01
  • 2012-12-27
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多