如何获取用于调用Google API的委托凭证对象? [英] How to get delegated credentials objects for invoking google apis?

本文介绍了如何获取用于调用Google API的委托凭证对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过API获取gsuite警报.我已经根据他们的 docs 创建了一个服务帐户,并且已分配了该帐户该服务帐户添加到我的Google云功能.

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)


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

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.

推荐答案

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

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.

还有带有的Google Cloud Platform Github存储库.一些有关此方法的文档.

这篇关于如何获取用于调用Google API的委托凭证对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆