使用 Python Oauthlib 通过服务帐户验证 Google API

2024-06-20

我不想使用适用于 Python 的 Google API 客户端库,但仍想使用 Python 访问 Google APIOauthlib https://github.com/idan/oauthlib.

创建服务帐户后谷歌开发者控制台 https://console.developers.google.com/iam-admin/serviceaccounts/project,我下载了包含要进行身份验证的信息的 json 文件,然后执行以下操作:

>>> import json
>>> from oauthlib.oauth2 import ServiceApplicationClient
>>> from requests_oauthlib import OAuth2Session

>>> json_file = json.load(open("google-project-credentials.json"))
>>> client_id = json_file['client_id']
>>> issuer = json_file['client_email']
>>> audience = 'https://www.googleapis.com/oauth2/v4/token'
>>> scope = 'https://www.googleapis.com/auth/tasks'
>>> private_key_id = json_file['private_key_id']
>>> private_key_pkcs8_pem = json_file['private_key']
>>> client = ServiceApplicationClient(client_id=client_id,issuer=issuer,audience=audience,private_key=private_key_pkcs8_pem)
>>> google = OAuth2Session(client_id, client=client)
>>> google.fetch_token(token_url)

调用 fetch_token 后,我收到此错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/antoinet/.virtualenvs/scraper/lib/python3.4/site-packages/requests_oauthlib/oauth2_session.py", line 244, in fetch_token
    self._client.parse_request_body_response(r.text, scope=self.scope)
  File "/Users/antoinet/.virtualenvs/scraper/lib/python3.4/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 409, in parse_request_body_response
    self.token = parse_token_response(body, scope=scope)
  File "/Users/antoinet/.virtualenvs/scraper/lib/python3.4/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 376, in parse_token_response
    validate_token_parameters(params)
  File "/Users/antoinet/.virtualenvs/scraper/lib/python3.4/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 383, in validate_token_parameters
    raise_from_error(params.get('error'), params)
  File "/Users/antoinet/.virtualenvs/scraper/lib/python3.4/site-packages/oauthlib/oauth2/rfc6749/errors.py", line 271, in raise_from_error
  raise cls(**kwargs)
oauthlib.oauth2.rfc6749.errors.InvalidGrantError: (invalid_grant) Invalid JWT: Failed audience check. The right audience is https://www.googleapis.com/oauth2/v4/token

然而,观众已经等于https://www.googleapis.com/oauth2/v4/token https://www.googleapis.com/oauth2/v4/token ...

当我尝试生成 jwt 时:

>>> client.prepare_request_body()

然后使用curl 运行bash 的结果: 卷曲 -d 'grant_type=urn............'https://www.googleapis.com/oauth2/v4/token https://www.googleapis.com/oauth2/v4/token

我收到以下错误:

{
  "error": "invalid_grant",
  "error_description": "Invalid JWT: Failed audience check. The right audience is https://www.googleapis.com/oauth2/v4/token"
}

我缺少什么?谢谢!


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Python Oauthlib 通过服务帐户验证 Google API 的相关文章

随机推荐