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

时间:2016-07-26 17:40:05

标签: python oauth-2.0 google-oauth google-cloud-platform pyjwt

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

Google developer console中创建服务帐户后,我下载了包含要进行身份验证的信息的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&#39; grant_type = urn ............&#39; 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"
}

我错过了什么?谢谢!

0 个答案:

没有答案