使用 oauth2client 创建 google api 凭据(来自具有范围和委托帐户的服务帐户)

Creating google api credentials (from service account with scope and delegated account) with oauth2client

要访问 GMail API(和个性化调用),我使用的是服务帐户(从 Google Cloud Platform 创建)。我的 json 文件看起来像这样

{
"type": "service_account",
"project_id": "[PROJECT-ID]",
"private_key_id": "[KEY-ID]"
"private_key": "-----BEGIN PRIVATE KEY-----\n[PRIVATE-KEY]\n-----END PRIVATE KEY-----\n",
"client_email": "[SERVICE-ACCOUNT-EMAIL]",
"client_id": "[CLIENT-ID]",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/[SERVICE-ACCOUNT-EMAIL]"
}

我也在使用 oauth2client 库来简化操作,但我找不到创建凭据然后指定范围和委托帐户的方法。

我试过了

from oauth2client import service_account

self._credentials = service_account.ServiceAccountCredentials.from_json(SERVICE_ACCOUNT_JSON_CONTENT)
self._credentials = self._credentials.create_scoped([u'https://www.googleapis.com/auth/gmail.send'])
self._credentials = self._credentials.create_delegated(MY_USER)
        self._client = discovery.build(u'gmail', u'v1', credentials=self._credentials)

但是我得到一个错误,因为它需要一个 PKCS-8 密钥。

我该怎么做? (如果有帮助,我的代码可以在 App Engine Flex 上运行)

谢谢

最后,由于 oauth2client 现在已被弃用,取而代之的是 google-auth,我做到了

from googleapiclient import discovery
from google.oauth2.service_account import Credentials

credentials = Credentials.from_service_account_file(PATH_TO_SERVICE_ACCOUNT_JSON,
                                                                  scopes=[u'https://www.googleapis.com/auth/gmail.send'])
delegated_credentials = self._credentials.with_subject(MY_USER)
client = discovery.build(u'gmail', u'v1', credentials=delegated_credentials)

并且有效 ;-)