首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用服务帐户从python代码访问GCP云函数?

如何使用服务帐户从python代码访问GCP云函数?
EN

Stack Overflow用户
提问于 2020-01-21 16:23:45
回答 3查看 2K关注 0票数 2

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

我的代码:

代码语言:javascript
运行
复制
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)

我得到了回应:

代码语言:javascript
运行
复制
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'

如何获得授权?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-02-17 01:17:10

您的示例代码正在生成访问令牌。下面是一个实际示例,该示例生成标识令牌,并使用该令牌调用云函数端点。该函数需要让云函数调用用于授权的服务帐户的调用角色。

代码语言:javascript
运行
复制
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)
票数 6
EN

Stack Overflow用户

发布于 2022-05-13 15:14:14

您需要获得身份令牌才能(http)触发云功能和

您的服务帐户至少需要有角色云函数调用者。

(为了尽可能安全地创建一个只能调用云函数的服务帐户,不要使用任何其他->来避免服务帐户密钥文件落入坏人手中时出现的问题。)

然后可以运行以下命令:

代码语言:javascript
运行
复制
import os
import google.oauth2.id_token
import google.auth.transport.requests
import requests

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'service_account_key_file.json' 

google_auth_request = google.auth.transport.requests.Request()
cloud_functions_url = 'https://europe-west1-your_project_id.cloudfunctions.net/your_function_name'

id_token = google.oauth2.id_token.fetch_id_token(
    google_auth_request, cloud_functions_url)

headers = {'Authorization': f'Bearer {id_token}'}
response = requests.get(cloud_functions_url, headers=headers)

print(response.content)

这个问题+答案也帮助了我:

访问Google函数的令牌?

如果您需要通过python访问令牌(而不是身份令牌),请在这里检查:

如何以编程方式使用python获取GCP Bearer令牌

票数 3
EN

Stack Overflow用户

发布于 2020-01-23 00:13:27

错误是因为调用没有经过身份验证。

因为现在调用来自您的本地主机,所以应该可以为您工作。

代码语言:javascript
运行
复制
curl https://REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME \
  -H "Authorization: bearer $(gcloud auth print-identity-token)"

这将使用您在本地主机上的gcloud上活动的帐户进行调用。

进行调用的帐户必须具有云函数调用的角色

今后,只需确保服务正在调用,此函数就具有上述角色。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59845302

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档