Google Cloud Function :: Service account :: JWT 令牌和不记名令牌

时间:2021-01-22 14:53:01

标签: google-cloud-functions jwt service-accounts

我有一个谷歌云函数。我也有一个网络应用程序。我想使用服务帐户验证对云功能的请求。

我有 json 密钥文件。

我知道我必须关注https://cloud.google.com/functions/docs/securing/authenticating#service-to-function。但这使我进入了不适用于谷歌云功能的 IAP 页面。

另一个类似的说明见https://developers.google.com/identity/protocols/oauth2/service-account

但如果我遵循 python 库代码,我最终会得到示例代码:

import googleapiclient.discovery

sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta3', credentials=credentials)


response = sqladmin.instances().list(project='exciting-example-123').execute()

这与调用云函数没有直接关系。

This 问题的答案有点符合我的要求,但使用的是仅适用于测试的 Call API。

此外,我想将此 API 公开给使用其他技术(如 .net)的多个应用程序。所以我相信对我来说最好的选择是使用 HTTP 方法(在同一页面上给出):

https://developers.google.com/identity/protocols/oauth2/service-account#httprest

但是无论我做什么,我都无法正确签名。

如果我在过去几天一直坚持这一点,我将不胜感激。

3 个答案:

答案 0 :(得分:1)

您可以像这样使用 Google auth 库


from google.oauth2.id_token import fetch_id_token
from google.auth.transport import requests

audience="my_audience"
r = requests.Request()

token=fetch_id_token(r,audience)

print(token)

fetch_id_token 方法将使用默认凭据

  1. 在环境变量 GOOGLE_APPLICATION_CREDENTIALS 中定义的服务帐号密钥文件
  2. 在 Google Cloud 环境中加载的服务帐号

答案 1 :(得分:0)

目前,我在 PHP 中关注了 this answer

在声明部分,我删除了范围。而是添加了 target_audience 的声明。 "target_audience" => "google-function-http-trigger"

云函数 http 触发器看起来像 https://us-central1-test-project-name.cloudfunctions.net/function-name",

这将提供所需的断言密钥。

然后我跟着https://developers.google.com/identity/protocols/oauth2/service-account#httprest拿到id_token

然后以 id_token 作为不记名令牌,我们就可以调用云函数了。

请注意,令牌的过期时间取决于“exp”声明中设置的时间。一旦过期,您必须重做生成新 id_token 的步骤

答案 2 :(得分:0)

<块引用>

我想使用服务帐户验证对云功能的请求。

我不确定我是否正确理解上下文,但我会尝试为该服务帐户分配一个 roles/cloudfunctions.invoker IAM 角色(用于在 Web 应用程序中运行您的代码) - 请参阅 {{3} } .

在这种情况下,该服务帐户下的代码“可以使用其公共 URL 调用 HTTP 函数”

我认为在这种情况下不需要 json 键。