我有一个App项目。
我也有一个谷歌云功能。
我想从App项目中调用Google函数。我只是不能让它起作用。
是的,如果我使函数完全公开(即将云函数设置为“允许所有通信量”,并为“allUsers”创建一个允许调用该函数的规则),它就能工作。但是如果我限制这两种设置中的任何一种,它就会立即停止工作,我得到403。
应用程序和函数在同一个项目中,所以我至少假设将函数设置为‘只允许内部通信’应该工作得很好,前提是我有一条关于“allUsers”的规则允许调用该函数。
这是如何工作的呢?人们通常如何从中调用(非公开的) Google函数?
发布于 2020-08-28 16:27:13
您需要一个指向函数url的ping的auth头。看起来应该是:
headers = {
....
'Authorization': 'Bearer some-long-hash-token'
}下面是如何获取令牌:
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")“只允许内部通信量”不像预期的那样工作。我的App应用程序和函数在同一个项目中,它不工作。我不得不打开“允许所有流量”,并使用标头方法。
示例:
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}"}
)发布于 2020-08-28 21:11:10
正如文档中所提到的,只允许内部通信量提到以下内容:
只允许来自同一项目中的VPC网络或VPC服务控制边界的请求。所有其他请求均被拒绝。
请注意,由于App标准是一种无服务器产品,它不是VPC的一部分,因此从该产品发出的请求不被视为“内部”调用,实际上调用来自实例的公共IP,因此您将得到HTTP403错误消息。
此外,使用VPC无服务器连接器也不能工作,因为这更像是连接VPC中资源的桥梁(比如VM或Memorystore实例),而不是云函数,因为这也是一个没有服务器的产品,而且它在VPC中没有IP。
我认为这里有三种选择:
发布于 2020-08-31 13:38:57
@GAEfan是正确的。
作为补充:我使用了官方的Google库来给我提供必要的标题。
const {GoogleAuth} = require('google-auth-library');
// Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc)
// this library will automatically choose the right client based on the environment.
const googleCloudFunctionURL = 'https://europe-west1-project.cloudfunctions.net/function';
(async function() {
const auth = new GoogleAuth();
let googleCloudFunctionClient = await auth.getIdTokenClient(googleCloudFunctionURL);
console.log(await googleCloudFunctionClient.getRequestHeaders(googleCloudFunctionURL));
})();https://stackoverflow.com/questions/63634151
复制相似问题