Wil*_*der 5 google-app-engine google-authentication google-cloud-functions
我有一个应用程序引擎项目。
我还有一个谷歌云功能。
我想从 App Engine 项目中调用 Google Cloud Function。我似乎无法让它发挥作用。
是的,如果我将函数完全公开(即将云函数设置为“允许所有流量”并为“allUsers”创建规则以允许调用该函数),它就可以工作。但是,如果我限制这两个设置中的任何一个,它就会立即停止工作,并收到 403 错误消息。
应用程序和函数位于同一个项目中,因此我至少假设将函数设置为“仅允许内部流量”应该可以正常工作,前提是我有“allUsers”规则允许调用该函数。
这是如何运作的?通常如何从 Google App Engine 调用(非公开)Google Cloud 函数?
您需要一个 auth 标头来 ping 到函数 url。它应该看起来像:
headers = {
....
'Authorization': 'Bearer some-long-hash-token'
}
Run Code Online (Sandbox Code Playgroud)
以下是获取令牌的方法:
import requests
token_response = requests.get(
'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=' +
'https://[your zone]-[your app name].cloudfunctions.net/[your function name]',
headers={'Metadata-Flavor': 'Google'})
return token_response.content.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)
“仅允许内部流量”无法按预期工作。我的 App Engine 应用程序与 Functions 位于同一项目中,但它不起作用。我必须打开“允许所有流量”,并使用标头方法。
例子:
def get_access_token():
import requests
token_response = requests.get(
'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=' +
'https://us-central1-my_app.cloudfunctions.net/my_function',
headers={'Metadata-Flavor': 'Google'})
return token_response.content.decode("utf-8")
def test():
url_string = f"https://us-central1-my_app.cloudfunctions.net/my_function?message=it%20worked"
access_token = get_access_token()
print(
requests.get(url_string, headers={'Authorization': f"Bearer {access_token}"}
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1387 次 |
| 最近记录: |