使用JWT为Gmail API授权Google服务帐户

时间:2019-06-16 10:23:08

标签: python-3.6 google-api-client jwt-auth

我正在尝试使用服务帐户凭据通过Gmail API(通过AWS lambda)访问我的电子邮件。我没有GSuite帐户,因此无法委托域范围的权限并模拟我的user@gmail.com帐户。

我使用没有OAuth的服务帐户授权,直接使用签名的JWT作为承载令牌。 [see]:https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth

我还启用了对该应用程序的所有Gmail访问权限,并使服务帐户成为控制台中的所有者角色。

我正在使用 google.auth.jwt 模块,但难以完全理解文档:[请参阅文档]:https://google-auth.readthedocs.io/en/latest/reference/google.auth.jwt.html#module-google.auth.jwt

这是我尝试过的:

from googleapiclient.discovery import build
from httplib2 import Http
from google.auth import crypt
from google.auth import jwt

audience = 'https://mail.google.com/' ## full access scope
credentials = jwt.Credentials.from_service_account_file(
    'credentials.json', audience=audience) # json credentials from api console - for service account
service = build('gmail', 'v1', credentials=credentials)

这给我一个401错误:

googleapiclient.errors.HttpError: <HttpError 401 when requesting https://www.googleapis.com/gmail/v1/users/me/messages?alt=json returned "Invalid Credentials">

credentials对象返回显示为有效,带有所有必要的元素,但是,我不知道如何使其“模拟”我的个人电子邮件。

0 个答案:

没有答案