[英]How do I either inherit authentication or authorize a Cloud Function in Python to access other Google APIs?
I locally developed a Python script that successfully downloads a file from Google Drive using the Drive API and then uploads a file using the Sheets API.我在本地开发了一个 Python 脚本,它成功地使用 Drive API 从 Google Drive 下载了一个文件,然后使用 Sheets API 上传了一个文件。
To authorize my script, I downloaded the credentials.json
and had my account authorized in IAM, and was using Oauth2.为了授权我的脚本,我下载了credentials.json
并在 IAM 中授权了我的帐户,并使用了 Oauth2。 Here's the relevant part of the script for authentication:这是用于身份验证的脚本的相关部分:
def main():
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
But I'm confused as to how to implement this on Cloud Functions.但我对如何在 Cloud Functions 上实现这一点感到困惑。 Does a Cloud Function start already authenticated? Cloud Function 启动是否已通过身份验证? I think my default service account is setup to access all the APIs.我认为我的默认服务帐户设置为可以访问所有 API。 I'm lost because I don't know where to start in terms of authentication.我迷路了,因为我不知道从哪里开始进行身份验证。
When you create your Cloud Function from the Console you need to click on dropdown to open the section ' Runtime, build, connections and security settings' from there you can choose the service account that the function will use.当您从控制台创建云 Function 时,您需要单击下拉菜单以打开“运行时、构建、连接和安全设置”部分,您可以从那里选择 function 将使用的服务帐户。 It might be the default App Engine service account or any other that has needed roles.它可能是默认的 App Engine 服务帐户或任何其他具有所需角色的帐户。 You don't need to implement authentication in your code.您不需要在代码中实施身份验证。
BTW there is also another method for authenticating while developing locally.顺便说一句,还有另一种在本地开发时进行身份验证的方法。 There is a feature in GCP SDK that's called deafault application credentials. GCP SDK 中有一项称为默认应用程序凭据的功能。 It's enough to export the variable GOOGLE_APPLICATION_CREDENTIALS and assign the path to the credentials.json file and your code will work (put in.bashrc to have it run always) you can read more here导出变量 GOOGLE_APPLICATION_CREDENTIALS 并将路径分配给 credentials.json 文件就足够了,您的代码将起作用(放入 .bashrc 以使其始终运行)您可以在此处阅读更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.