gpt4 book ai didi

Python OAuth 错误 "Invalid Grant"

转载 作者:行者123 更新时间:2023-12-05 06:44:42 28 4
gpt4 key购买 nike

我在一家小公司工作,该公司的邮件通过 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com