从云功能调用Cloud Run:IAM认证

luh*_*uhu 8 firebase google-cloud-platform google-cloud-functions google-iam google-cloud-run

我通过 Google Cloud Run 部署了一个小型 HTTP 端点。当我关闭身份验证时它工作正常。

我现在想将其打开,以便只能由我的 Firebase 云函数调用。如果我理解正确的话,我只需在 Cloud Run 的 IAM 设置中添加正确的服务帐户邮件地址作为“Cloud Run 调用者”即可。但哪个地址是正确的呢?

我已尝试在 Firebase 控制台 -> 项目设置 -> 服务帐户中找到的所有地址。

wlh*_*hee 6

我想你可以检查一下具体的firebase功能。在 UI 中,应列出所使用的服务帐户。

默认情况下,GCF 函数均使用 <project_id>@appspot.gserviceaccount.com

  • 除此之外,请确保您阅读 https://cloud.google.com/run/docs/authenticating/service-to-service,因为向服务帐户添加权限神奇地不会使其只能由该功能访问。该函数需要更改代码以将身份令牌添加到发送到 Cloud Run 的请求。 (3认同)

luh*_*uhu 2

感谢@AhmetB - Google 和@whlee 的回答,我让它工作了。基本上,向请求添加授权承载令牌就足够了,您可以从特殊端点获取该令牌: https: //cloud.google.com/run/docs/authentication/service-to-service#nodejs

然后,您只需将该函数的服务帐户添加到 Cloud Run 容器的 IAM 列表中即可: <project_id>@appspot.gserviceaccount.com

Nodejs 示例使用已弃用的请求库,因此这是我使用 axios 的版本:

    const getOAuthToken = async (receivingServiceURL: string): Promise<string> => {

      // Set up metadata server request
      const metadataServerTokenURL = 'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=';
      const uri = metadataServerTokenURL + receivingServiceURL;
      const options = {
        headers: {
          'Metadata-Flavor': 'Google'
        }
      };

      return axios.get(uri, options)
        .then((res) => res.data)
        .catch((error) => Promise.reject(error));
    }
Run Code Online (Sandbox Code Playgroud)

然后您可以在实际请求中使用令牌:

    const url = `...`;
    const token = await getOAuthToken(url);

    axios.post(url, formData, {
        headers: {
            Authorization: `Bearer ${token}`,
        }
    }).then(...).catch(...);
Run Code Online (Sandbox Code Playgroud)