小编Vol*_*t93的帖子

如何使用服务帐户从Python代码访问GCP云功能?

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

我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

我收到了回复:

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'

Run Code Online (Sandbox Code Playgroud)

如何获得授权?

service-accounts google-cloud-platform google-cloud-functions google-iam google-cloud-iam

2
推荐指数
1
解决办法
3167
查看次数