How to get delegated credentials objects for invoking google apis?

不想你离开。 提交于 2021-02-19 05:21:40

问题


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('admin@alertcenter1.bigr.name').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.


回答1:


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.




回答2:


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 = 'username@example.com'

credentials = credentials.with_subject(impersonate)

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


来源:https://stackoverflow.com/questions/55356089/how-to-get-delegated-credentials-objects-for-invoking-google-apis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!