Python OAuth 错误 "Invalid Grant"

标签 python oauth http-status-code-400 service-accounts

我在一家小公司工作,该公司的邮件通过 Google 托管。作为负责管理员工帐户的管理员之一,我正在尝试使用 Google API 和一个或多个专用服务帐户自动执行某些任务。我根据 Google 提供的文档编写了下面的简短 Python 脚本来请求访问 token ,但我仍然收到“invalid_grant”错误。

我做了以下事情:

  • 以服务帐户登录 Google Developers Console 并创建项目
  • 创建了服务帐户类型的客户端 ID
  • 登录到 Google 管理控制台并添加了我希望帐户能够访问的客户电子邮件地址和范围 URL

在线搜索得到的答案表明机器的系统时间已关闭,已超过刷新 token 的限制或已使用客户端 ID 而不是客户端电子邮件。在运行脚本之前,我已经在 Windows 机器和 Linux 机器上同步了时间,但出现了同样的错误。我什至没有获得访问 token ,所以我怀疑是否已超出刷新限制。如下所示,iss 值设置为以“@developer.gserviceaccount.com”结尾的客户端电子邮件地址。

我怀疑我还遗漏了一些其他东西,而且由于我是 Python 新手,我怀疑它非常简单。也许有人可以提供帮助?

import json
import time
import base64
import requests
from datetime import datetime

utc = datetime.utcnow()
iat = time.mktime(utc.timetuple())
exp = iat + 3600

jwt_header = {
    "alg":"RS256",
    "typ":"JWT"
}

jwt_claim_set = {
    "iss":"pleasehelpme@developer.gserviceaccount.com",
    "scope":"https://www.googleapis.com/auth/admin.directory.user",
    "aud":"https://www.googleapis.com/oauth2/v3/token",
    "iat":int(iat),
    "exp":int(exp),
    "sub":"someadminfrustrated@googleoauth.com"
}

jwt_jws = bytearray(str(jwt_header) + '.' + str(jwt_claim_set))

jwt_unencoded = str(jwt_header) + '.' + str(jwt_claim_set) + '.' +     str(jwt_jws)
jwt_encoded = base64.urlsafe_b64encode(str(jwt_unencoded))

url = 'https://www.googleapis.com/oauth2/v3/token'
headers = {
    'content-type': 'application/x-www-form-urlencoded'
}

payload = {
    'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion': jwt_encoded
}

response = requests.post(url, headers=headers, params=payload)

print response
print response.json()

输出如下:

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

最佳答案

我会查看输出的 http 和 url 来确定,但看起来您确实遇到了身份验证问题。

我遇到了一个类似但不那么复杂的问题,无法通过 python 脚本获取我的 Google Developer 凭据。我最终使用我的 Chrome 浏览器 cookie 和这个脚本来完成那部分:http://n8henrie.com/2014/05/decrypt-chrome-cookies-with-python/

让一切变得非常简单:

url = 'http://www.example.com'
s = requests.Session()
cookies = pyCookieCheat.chrome_cookies(url)
s.get(url, cookies = cookies)

关于Python OAuth 错误 "Invalid Grant",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28074991/

相关文章:

ruby-on-rails-3 - Heroku 和 Rails 3 的零星 400 错误请求错误 nginx/0.7.67

python - Pandas- ValueError : Usecols do not match columns, 列预期但未找到

python - 比较当前元组列表和下一个元组列表的值

Facebook access_token 无效?

python - 使用 python requests.post 函数时错误请求错误 400

c# - React + ASP.Net-Core CORS 问题

python - 如何避免 Numpy 类型转换?

python - 如何在等待 getch 的同时运行副任务?

iphone - 是否有针对 Objective C 的预编译 OAuth 框架可供下载?

security - 单页 Web 应用程序、CORS 和安全问题