3

我不想使用 Python 的 Google API 客户端库,但仍想使用Oauthlib在 Python 中访问 Google API 。

Google 开发人员控制台中创建服务帐户后,我下载了包含验证信息的 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 ...

当我尝试生成 jwt 时:

>>> client.prepare_request_body()

然后使用 curl 从 bash 运行结果: curl -d 'grant_type=urn............' 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"
}

我错过了什么?谢谢!

4

0 回答 0