himanshu219
himanshu219

Reputation: 664

How to get delegated credentials objects for invoking google apis?

I am trying to fetch gsuite alerts via API. I have created a service account as per their docs and I have assigned that service account to my google cloud function.

I do not want to use environment variables or upload credentials along with source code but I want leverage default service account used by function.

from googleapiclient.discovery import build

def get_credentials():

    # if one knows credentials file location(when one uploads the json credentials file or specify them in environment variable) one can easily get the credentials by specify the path.
    # In case of google cloud functions atleast I couldn't find it the path as the GOOGLE_APPLICATION_CREDENTIALS is empty in python runtime

    # the below code work find if one uncomments the below line
    #credentials = ServiceAccountCredentials.from_json_keyfile_name(key_file_location)

    credentials = < how to get default credentials object for default service account?>

    delegated_credentials = credentials.create_delegated('[email protected]').create_scoped(SCOPES)
    return delegated_credentials

def get_alerts(api_name, api_version, key_file_location=None):

    delegated_credentials = get_credentials()
    alertcli = build(api_name, api_version, credentials=delegated_credentials)
    resp = alertcli.alerts().list(pageToken=None).execute()
    print(resp)


Is there any way I can create a default credentials object. I have tried using from google.auth import credentials but this does not contain create_delegated function and I have also tried ServiceAccountCredentials() but this requires signer.

Upvotes: 4

Views: 4125

Answers (2)

vkopio
vkopio

Reputation: 1014

You can use the google.auth.default function to get the default credentials and use them to make an IAM signer which can be used to create new service account credentials which has the delegated email adress as subject. I have a more detailed answer for a similar question.

There is also Google Cloud Platform Github repository with some documentation about this method.

Upvotes: 2

John Hanley
John Hanley

Reputation: 81356

Here is an example to use the Gmail API with delegated credentials. The service account credentials will need "Enable G Suite Domain-wide Delegation" enabled.

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

credentials = service_account.Credentials.from_service_account_file(
                        credentials_file,
                        scopes=['https://www.googleapis.com/auth/gmail.send'])

impersonate = '[email protected]'

credentials = credentials.with_subject(impersonate)

service = build('gmail', 'v1', credentials=credentials)

Upvotes: 5

Related Questions