如何获取委托的凭据对象以调用Google API?

时间:2019-03-26 11:30:56

标签: python google-cloud-platform google-cloud-functions service-accounts google-python-api

我正在尝试通过API来获取gsuite警报。我已经按照他们的docs创建了一个服务帐户,并将该服务帐户分配给了我的Google云功能。

我不想使用环境变量或将凭据与源代码一起上传,但是我想利用函数使用的默认服务帐户。

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)


有什么方法可以创建默认的凭据对象。我尝试使用 从google.auth导入凭据,但这不包含create_delegated函数和 我也尝试了ServiceAccountCredentials(),但这需要签名者。

2 个答案:

答案 0 :(得分:1)

您可以使用google.auth.default函数来获取默认凭据,并使用它们来创建IAM签名者,该签名者可以用于创建新的服务帐户凭据,该凭据的委派电子邮件地址为subject。我有一个类似问题的more detailed answer

还有关于此方法的some documentation的Google Cloud Platform Github存储库。

答案 1 :(得分:0)

以下是将Gmail API与委派凭据一起使用的示例。服务帐户凭据将需要启用“启用G Suite域范围委派”。

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)