Search code examples
google-oauthservice-accountsapp-engine-flexibleoauth2client

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


To access GMail API (and personify calls) I'm using a service account (created from Google Cloud Platform). The json file I have looks like this

{
"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]"
}

I'm also using the oauth2client library to make it easier but I can't find a way to create the credentials and then specify a scope and a delegated account.

I tried

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)

But I get an error cause it expects a PKCS-8 key.

How can I do that ? (My code runs on App Engine Flex if that helps)

Thanks


Solution

  • Finally, since oauth2client is now deprecated in favor of google-auth, I did

    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)
    

    and it worked ;-)