gpt4 book ai didi

google-cloud-platform - 如何使用服务帐户从 python 代码访问 GCP 云功能?

转载 作者:行者123 更新时间:2023-12-05 08:51:30 24 4
gpt4 key购买 nike

我已经部署了一个简单的 GCP 云函数,它返回“Hello World!”。我需要这个功能得到授权。我取消标记“允许未经身份验证的调用”复选框,因此只有经过身份验证的调用才能调用此代码。我还创建了服务帐户并赋予了下一个角色: - 云函数调用器 - 云函数服务代理

我的代码:

from google.oauth2 import service_account
from google.auth.transport.urllib3 import AuthorizedHttp

if __name__ == '__main__':
credentials = service_account.Credentials.from_service_account_file('service-account.json',
scopes=['https://www.googleapis.com/auth/cloud-platform'],
subject='service-acc@<project_id>.iam.gserviceaccount.com')
authed_session = AuthorizedHttp(credentials)
response = authed_session.urlopen('POST', 'https://us-central1-<project_id>.cloudfunctions.net/main')
print(response.data)

我得到了回应:

b'\n<html><head>\n<meta http-equiv="content-type" content="text/html;charset=utf-8">\n<title>401 Unauthorized</title>\n</head>\n<body text=#000000 bgcolor=#ffffff>\n<h1>Error: Unauthorized</h1>\n<h2>Your client does not have permission to the requested URL <code>/main</code>.</h2>\n<h2></h2>\n</body></html>\n'

如何获得授权?

最佳答案

您的示例代码正在生成访问 token 。下面是一个生成身份 token 并使用该 token 调用 Cloud Functions 端点的真实示例。该函数需要具有用于授权的服务帐户的 Cloud Function Invoker 角色。

import json
import base64
import requests

import google.auth.transport.requests
from google.oauth2.service_account import IDTokenCredentials

# The service account JSON key file to use to create the Identity Token
sa_filename = 'service-account.json'

# Endpoint to call
endpoint = 'https://us-east1-replace_with_project_id.cloudfunctions.net/main'

# The audience that this ID token is intended for (example Google Cloud Functions service URL)
aud = 'https://us-east1-replace_with_project_id.cloudfunctions.net/main'

def invoke_endpoint(url, id_token):
headers = {'Authorization': 'Bearer ' + id_token}

r = requests.get(url, headers=headers)

if r.status_code != 200:
print('Calling endpoint failed')
print('HTTP Status Code:', r.status_code)
print(r.content)
return None

return r.content.decode('utf-8')

if __name__ == '__main__':
credentials = IDTokenCredentials.from_service_account_file(
sa_filename,
target_audience=aud)

request = google.auth.transport.requests.Request()

credentials.refresh(request)

# This is debug code to show how to decode Identity Token
# print('Decoded Identity Token:')
# print_jwt(credentials.token.encode())

response = invoke_endpoint(endpoint, credentials.token)

if response is not None:
print(response)

关于google-cloud-platform - 如何使用服务帐户从 python 代码访问 GCP 云功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59845302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com