【问题标题】:Google Cloud Function :: Service account :: JWT token and Bearer tokenGoogle Cloud Function :: Service account :: JWT token 和 Bearer token
【发布时间】:2021-01-22 14:53:01
【问题描述】:

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

我有 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 问题的答案有点符合我的要求,但使用的是仅适用于测试的调用 API。

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

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

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

任何帮助解决这个问题都将受到高度赞赏,因为过去几天我一直坚持这一点。

【问题讨论】:

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


    【解决方案1】:

    您可以像这样使用 Google 身份验证库

    
    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 环境中加载的服务帐号

    【讨论】:

    • 感谢您的回复。此方法是否假定我的应用程序托管在我的 Google Cloud 项目中?
    • 不仅如此。如果托管在 Google Cloud 上,则使用该服务的服务帐号。如果在其他地方,在您的计算机或其他环境中,您可以使用服务帐户密钥文件,并定义指向它的 GOOGLE_APPLICATION_CREDENTIALS
    【解决方案2】:

    目前,我在 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作为bearer token,我们就可以调用云函数了。

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

    【讨论】:

      【解决方案3】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 2021-08-02
        • 2021-04-28
        • 2017-03-15
        • 2022-01-24
        • 2021-05-10
        • 2015-10-26
        • 1970-01-01
        • 1970-01-01
        • 2019-10-15
        相关资源
        最近更新 更多